How do you access the query string in Flask routes?
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')
Capture URL with query string as parameter in Flask route
the path
pattern will let you capture more complicated route patterns like URLs:
@app.route('/catch/<path:foo>')
def catch(foo):
print(foo)
return foo
The data past the ?
indicate it's a query parameter, so they won't be included in that patter. You can either access that part form request.query_string
or build it back up from the request.args
as mentioned in the comments.
Get a variable from the URL in a Flask route
This is answered in the quickstart of the docs.
You want a variable URL, which you create by adding <name>
placeholders in the URL and accepting corresponding name
arguments in the view function.
@app.route('/landingpage<id>') # /landingpageA
def landing_page(id):
...
More typically the parts of a URL are separated with /
.
@app.route('/landingpage/<id>') # /landingpage/A
def landing_page(id):
...
Use url_for
to generate the URLs to the pages.
url_for('landing_page', id='A')
# /landingpage/A
You could also pass the value as part of the query string, and get it from the request, although if it's always required it's better to use the variable like above.
from flask import request
@app.route('/landingpage')
def landing_page():
id = request.args['id']
...
# /landingpage?id=A
How can I get the named parameters from a URL using Flask?
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')
Flask - how to get query string parameters into the route parameters
You would need to use JavaScript to achieve this so your template would become:
<input type='text' id='address'>
<button onclick="sendUrl();">submit</button>
<script>
function sendUrl(){
window.location.assign("/sales/"+document.getElementById("address").value);
}
</script>
and your routes similar to before:
@app.route('/sales/')
@app.route('/sales/<address>')
def get_sales(address="Nowhere"):
# do some magic here
# render template of sales
return "The address is "+address
However, this is not the best way of doing this kind of thing. An alternative approach is to have flask serve data and use a single-page-application framework in javascript to deal with the routes from a user interface perspective.
Get query string as function parameters on flask
If you are willing to write a decorator, anything is possible:
from functools import wraps
def extract_args(*names, **names_and_processors):
user_args = ([{"key": name} for name in names] +
[{"key": key, "type": processor}
for (key, processor) in names_and_processors.items()])
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
final_args, final_kwargs = args_from_request(user_args, args, kwargs)
return f(*final_args, **final_kwargs)
return wrapper
return decorator if len(names) < 1 or not callable(names[0]) else decorator(names[0])
def args_from_request(to_extract, provided_args, provided_kwargs):
# Ignoring provided_* here - ideally, you'd merge them
# in whatever way makes the most sense for your application
results = {}
for arg in to_extract:
result[arg["key"]] = request.args.get(**arg)
return provided_args, results
Usage:
@app.route("/somewhere")
@extract_args("gender", age=int)
def somewhere(gender, age):
return jsonify(gender=gender, age=age)
How to process GET Query String with Flask
Yes. request.args
is a MultiDict
:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route("/")
def hello():
all_args = request.args.lists()
return jsonify(all_args)
Flask-Login | url query string arg 'next'
You need an else statement for the case that _next startswith '/'
In your case _next starts with '/' (or is None) and your given code goes to the return at the bottom:
return render_template('auth/login.html')
using the existing _next as arg inside the url, that is why it sends you to
http://127.0.0.1:5000/auth/login?next=%2Fmedic%2F
So complete the following part of your code with an else statement, othwerise it will send you at the return statement at the bottom (return render_template('auth/login.html')
) every time your current condition is not met:
if _next is None or not _next.startswith('/'):
_next = url_for("medic.home")
print(_next)
return redirect(url_for('medic.home'))
Related Topics
Performance of Pandas Apply VS Np.Vectorize to Create New Column from Existing Columns
How to Use the Same Python Virtualenv on Both Windows and Linux
Boto3 Client Noregionerror: You Must Specify a Region Error Only Sometimes
Why Is a List Comprehension So Much Faster Than Appending to a List
Python Date String to Date Object
Unnest (Explode) a Pandas Series
How to Remove Stop Words Using Nltk or Python
How to Make a Multi-Color Line in Matplotlib
How to Test the Membership of Multiple Values in a List
Why Do We Use _Init_ in Python Classes
Sending Messages with Telegram - APIs or Cli
How Is the 'Is' Keyword Implemented in Python
Django Set Default Form Values
Why Do Integers in Database Row Tuple Have an 'L' Suffix