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")
To access an individual known param passed in the query string, you can use request. args. get('param') .
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?
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With