How can I get the named parameters from a URL using Flask?
When the user accesses this URL running on my flask app, I want the web service to be able to handle the parameters specified after the question mark:
http://10.1.1.1:5000/login?username=alex&password=pw1
#I just want to be able to manipulate the parameters
@app.route('/login', methods=['GET', 'POST'])
def login():
username = request.form['username']
print(username)
password = request.form['password']
print(password)
Solution 1:
Use request.args
to get parsed contents of query string:
from flask import request
@app.route(...)
def login():
username = request.args.get('username')
password = request.args.get('password')
Solution 2:
The URL parameters are available in request.args
, which is an ImmutableMultiDict that has a get
method, with optional parameters for default value (default
) and type (type
) - which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)
from flask import request
@app.route('/my-route')
def my_route():
page = request.args.get('page', default = 1, type = int)
filter = request.args.get('filter', default = '*', type = str)
Examples with the code above:
/my-route?page=34 -> page: 34 filter: '*'
/my-route -> page: 1 filter: '*'
/my-route?page=10&filter=test -> page: 10 filter: 'test'
/my-route?page=10&filter=10 -> page: 10 filter: '10'
/my-route?page=*&filter=* -> page: 1 filter: '*'
Solution 3:
You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments
@app.route('/<name>')
def my_view_func(name):
return name