How to get form data in Flask
In Flask, we can use the request object to get form data submitted in an HTTP POST request. The request object is part of the flask package and provides access to information about incoming requests. We can import this module using the following command:
The code example given below has the following file structure:
-
templates/form.html: This markup file contains a form. This file will be used to submit data to the application. -
templates/success.html: This markup file will get the data from the application and render the data. -
/app/App.py: This file contains the core logic of the Flask application. This file will use the data from the form.
Example
Explanation
The example code works as follows:
-
Line 9: The
submit_form()method as a decoration ofmethod=['POST']defines that this method will only accept thePOSTrequests. -
Line 11-13: In this method, we use
request.form.get()to get the data from the form. Therequestis a library fromflaskandrequest.formcontains a dictionary containing all the values submitted using the form. This dictionary has the following structure: -
Line 14-15: Names of form fields as the keys of the dictionary. Submitted values as the values against keys in the dictionary
-
Line 15: Finally, we use the
render_template()function to render a template. This is also available in theflaskpackage. This function is used to generate HTML files. This method accepts the file name to render and another optional parameter for data that can be accessed using theJinja2syntax ({{name}}) in the HTML files.
Note: To learn about Flask, see this Answer.
Free Resources