Multiple parameters in Flask approute

user2058205 picture user2058205 · Mar 3, 2013 · Viewed 84.5k times · Source

How to write the flask app.route if I have multiple parameters in the URL call?

Here is my URL I am calling from AJax:

http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure

I was trying to write my flask app.route like this:

@app.route('/test/<summary,change>', methods=['GET']

But this is not working. Can anyone suggest me how to mention the app.route?

Answer

GMarsh picture GMarsh · Dec 28, 2016

The other answers have the correct solution if you indeed want to use query params. Something like:

@app.route('/createcm')
def createcm():
   summary  = request.args.get('summary', None)
   change  = request.args.get('change', None)

A few notes. If you only need to support GET requests, no need to include the methods in your route decorator.

To explain the query params. Everything beyond the "?" in your example is called a query param. Flask will take those query params out of the URL and place them into an ImmutableDict. You can access it by request.args, either with the key, ie request.args['summary'] or with the get method I and some other commenters have mentioned. This gives you the added ability to give it a default value (such as None), in the event it is not present. This is common for query params since they are often optional.

Now there is another option which you seemingly were attempting to do in your example and that is to use a Path Param. This would look like:

@app.route('/createcm/<summary>/<change>')
def createcm(summary=None, change=None):
    ...

The url here would be: http://0.0.0.0:8888/createcm/VVV/Feauure

With VVV and Feauure being passed into your function as variables.

Hope that helps.