Every form of the query string retrievable from flask request object as described in O'Reilly Flask Web Devleopment:
From O'Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:
from flask import request
request
is an object exposed by Flask as a context variable named (you guessed it) request
. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.
You have quite a few request
attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O'Reilly book of that attribute.
First there is args
which is "a dictionary with all the arguments passed in the query string of the URL." So if you want the query string parsed into a dictionary, you'd do something like this:
from flask import request
@app.route('/'):
queryStringDict = request.args
(As others have pointed out, you can also use .get('<arg_name>')
to get a specific value from the dictionary)
Then, there is the form
attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form
is "A dictionary with all the form fields submitted with the request." I say that to say this: there is another dictionary attribute available in the flask request object called values
. values
is "A dictionary that combines the values in form
and args
." Retrieving that would look something like this:
from flask import request
@app.route('/'):
formFieldsAndQueryStringDict = request.values
(Again, use .get('<arg_name>')
to get a specific item out of the dictionary)
Another option is query_string
which is "The query string portion of the URL, as a raw binary value." Example of that:
from flask import request
@app.route('/'):
queryStringRaw = request.query_string
Then as an added bonus there is full_path
which is "The path and query string portions of the URL." Por ejemplo:
from flask import request
@app.route('/'):
pathWithQueryString = request.full_path
And finally, url
, "The complete URL requested by the client" (which includes the query string):
from flask import request
@app.route('/'):
pathWithQueryString = request.url
Happy hacking :)