Home > Software design >  Python Flask: How to easily consume dozens of HTML form fields and use them in a DB call?
Python Flask: How to easily consume dozens of HTML form fields and use them in a DB call?

Time:07-14

I have a form with several dozen fields and in my route I collect them as follows

conditions_angina= request.form["conditions-angina"]
conditions_cancer= request.form["conditions-cancer"]
conditions_stroke= request.form["conditions-stroke"]
...

Then later I do what I need to do with my DB insert

sql = EXEC uspInsertData ?,?,?....
params = (conditions_angina,conditions_cancer,conditions_stroke...
sql_result = Conn.testsql(db="TestPython", sql=sql, params=params)

This all works fine but I was wondering if there was a cleaner way to do this for several dozen fields or any number of fields

We don't use WTForms we just add them manually for now with Bootstrap 4 styling

CodePudding user response:

Since you have a form you can use request.form to get all of the keys/values from the form (see request.form usage here) instead of specifically assigning each form field to a variable like you're doing now. It's an ImmutableMultiDict ref here.

In your route or endpoint to get all of the fields it would look like this:

conditions = request.form

Now your conditions object will look like:

conditions = {"form_field_1": "form_value_1", "form_field_2": "form_value_2"}

from which you can insert your data accordingly.

CodePudding user response:

You can use SQLAlchemy ORM. Using SQLAlchemy one can perform database operations using Object Oriented Paradigm.
Flask SQLAlchemy

  • Related