GET parameters with Flask

Creating a web application and passing parameters between pages is the most normal action. Here we are going to explain how to handle GET parameters with Flask.

The first thing of all will be to create a route that will paint a form for us. What this route does is render a template with a form using the render_template() method

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

The form is still a form HTML. Of course, the sending method is GET and the destination or action attribute will be the same route.



Now we will have to modify our route to see if there are parameters. Since if there are no parameters we will repaint the form. To be able to retrieve the GET parameters with Flask we manipulate the request.arg object. Specifically the .get() method. This method will receive the name of the form parameter as a value.

 name = request.args.get('name')

In case it fails we repaint the form:

@app.route('/greeting',methods=['GET'])
def form():
    try:
        name = request.args.get('name')        
    except:
        return render_template('form_get.html')

And if we want to control something else, if the GET parameter is empty we also repaint the form:

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

    #We check if the parameter comes by GET
    try:
        name = request.args.get('name')

        if (name != ''):
            return 'Hello ' + name
        else:
            return render_template('form_get.html')
    except:
        return render_template('form_get.html')

In this way we have already seen how simple it is to handle GET parameters with Flask.

Leave a Comment