pythondatabasesqlalchemypyramiddeform

Is there a way to map data from form to insert in to database without explicitly defining each variable?


I have made a really long form with the help of colander alchemy and deform.

This form has 100 or so fields and currently the only way I know to add the data back to the database once form is submitted is to explicitly re-define each variable and then add that to the database but there must be a better way.


#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?

Solution

  • So, you have a dict (request.params) and want to pass the key-value pars from that dict to a function? Python has a way to do that using **kwargs syntax:

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

    (this works also because SQLAlchemy provides a default constructor which assigns the passed values to the mapped columns, no need to define it manually)

    Of course, this is a naive approach which will only work for the simplest use-cases - for example, it may allow passing parameters not defined in your schema which may create a security problem; the field names in your schema must match the field names in your SQLAlchemy model; it may not work with lists (i.e. multiple values with the same name which you can access via request.params.get_all(name)).