2

在滤锅炼金术和变形的帮助下,我制作了一个非常长的表格。

这个表单有 100 个左右的字段,目前我知道在提交表单后将数据添加回数据库的唯一方法是显式地重新定义每个变量,然后将其添加到数据库中,但必须有更好的方法。


#my schema 

class All(colander.MappingSchema):
                setup_schema(None,atr)
                atrschema =atr.__colanderalchemy__
                setup_schema(None,chemicals)
                chemicalsschema =chemicals.__colanderalchemy__
                setup_schema(None,data_aquisition)
                data_aquisitionschema =data_aquisition.__colanderalchemy__
                setup_schema(None,depositor)
                depositorschema =depositor.__colanderalchemy__
                setup_schema(None,dried_film)
                dried_filmschema =dried_film.__colanderalchemy__

form = All()
form = deform.Form(form,buttons=('submit',))

# this is how I get it to work by redefining each field but there must be a better way

if 'submit' in request.POST:

   prism_material = request.params['prism_material']
   angle_of_incidence_degrees = 
   request.params['angle_of_incidence_degrees']
   number_of_reflections = request.params['number_of_reflections']
   prism_size_mm = request.params['prism_size_mm']
   spectrometer_ID = 6

   page = atr (spectrometer_ID=spectrometer_ID,prism_size_mm=prism_size_mm,number_of_reflections=number_of_reflections,angle_of_incidence_degrees=angle_of_incidence_degrees,prism_material=prism_material)

   request.dbsession.add(page)




Would like to somehow just be able to remap all of that 'multi dictionary' that is returned back to the database?
4

1 回答 1

2

那么,您有一个 dict ( request.params) 并希望将键值解析从该 dict 传递给一个函数?**kwargs Python 有一种方法可以使用语法来做到这一点:

if 'submit' in request.POST:
   page = Page(spectrometer_ID=6,**request.params)   
   request.dbsession.add(page)

(这也有效,因为 SQLAlchemy 提供了一个默认构造函数,它将传递的值分配给映射列,无需手动定义)

当然,这是一种幼稚的方法,仅适用于最简单的用例 - 例如,它可能允许传递架构中未定义的参数,这可能会产生安全问题;架构中的字段名称必须与 SQLAlchemy 模型中的字段名称匹配;它可能不适用于列表(即您可以通过 request.params.get_all(name) 访问的具有相同名称的多个值)。

于 2019-06-20T21:23:52.007 回答