POST parameters with Flask

Creating a form in a POST application will help us learn how to control the data we upload. Here we are going to see how we can handle the POST parameters with Flask.

The first thing will be to create a route that accepts a GET request which returns a form. We are going to render the form using a render_template() method

@app.route('/greeting',methods=['GET'])
def form():
    return render_template('form.html')

The form template will be very simple. The important thing is that the method is POST and that the action field is pointing to the same route /greeting




It is very important to put the name attributes in the form, since it will be that attribute that we use to retrieve the value.

Now we create the same route again, but in this case so that it accepts POST requests.

@app.route('/greeting',methods=['POST'])
def greeting():

To access the information about the form attributes we use the request.form object. This object has the attributes in a collection. So we will recover the value of the name and surname fields of the form using the following code:

 name = request.form['name']
 lastname = request.form['lastname']

We will only have something like returning them as a response:

@app.route('/greeting',methods=['POST'])
def greeting():
    name = request.form['name']
    lastname = request.form['lastname']
    return 'Hello ' + first name + ' ' + last name

In this way we have already managed to manipulate and recover POST parameters with Flask.