Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access the query string in Flask routes?

How do you access query parameters or the query string in Flask routes? It's not obvious from the Flask documentation.

The example route /data below illustrates the context that I would like to access that data. If someone requests something like example.com/data?abc=123, I would like access to the string ?abc=123 or to be able to retrieve the value of parameters like abc.

@app.route("/data") def data():     # query_string = ???     return render_template("data.html") 
like image 413
Tampa Avatar asked Aug 02 '12 09:08

Tampa


People also ask

How do I access query string in Flask?

To access an individual known param passed in the query string, you can use request. args. get('param') .

What is query string in Flask?

David Landup. Query Parameters are part of the Query String - a section of the URL that contains key-value pairs of parameters. Typically, parameters are sent alongside GET requests to further specify filters on the operation: www.example.com/search?


2 Answers

from flask import request  @app.route('/data') def data():     # here we want to get the value of user (i.e. ?user=some-value)     user = request.args.get('user') 
like image 181
Kracekumar Avatar answered Sep 28 '22 17:09

Kracekumar


The full URL is available as request.url, and the query string is available as request.query_string.decode().

Here's an example:

from flask import request  @app.route('/adhoc_test/') def adhoc_test():      return request.query_string 

To access an individual known param passed in the query string, you can use request.args.get('param'). This is the "right" way to do it, as far as I know.

ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.

like image 26
Lyndsy Simon Avatar answered Sep 28 '22 15:09

Lyndsy Simon