问题
I have the following function with multiple routes possible :
@bp.route('/list/', defaults={'status': None, 'time': None, 'search': None})
@bp.route('/list/lot/', defaults={'status': None, 'search': None, 'time': None})
@bp.route('/list/lot/<string:time>/', defaults={'status': None, 'search': None})
@bp.route('/list/lot/<string:time>/<string:status>', defaults={'search': None})
@bp.route('/list/lot/<string:time>/<string:status>?search=<path:search>')
@login_required
def index(status, time, search):
print(search)
All the routes works well, except the last one. I have the URL likes this :
http://192.168.10.88:5000/list/lot/OLDER/NEW?search=test
And I don't understand why, the print always return None
.
Any ideas ?
Thanks
回答1:
You can use request
or request.query_string
if you want to get the query string:
from flask import request
@bp.route('/list/', defaults={'status': None, 'time': None, 'search': None})
@bp.route('/list/lot/', defaults={'status': None, 'search': None, 'time': None})
@bp.route('/list/lot/<string:time>/', defaults={'status': None, 'search': None})
@bp.route('/list/lot/<string:time>/<string:status>', defaults={'search': None})
@bp.route('/list/lot/<string:time>/<string:status>?search=<path:search>')
@login_required
def index(status, time, search):
print(request.query_string, request.args.get('search'), time, status)
# b'search=test' test OLDER NEW
return 'OK'
remarks how I used request
to get the value of search : request.args.get('search')
.
Here is another approach that I find simpler and cleaner:
@bp.route('/list/lot/parameters')
@login_required
def index():
print(request.args.get('time'), request.args.get('status'), request.args.get('search'))
return 'OK'
The Url look like this:
http://192.168.10.88:5000/list/lot/parameters?time=OLDER&status=NEW&search=test
回答2:
The part after the ?
is the query string. I'm 99% sure Flask strips the query string off when matching routes (I couldn't confirm this in the docs hence the 1%). This means that the following urls are identical when matching a route.
http://192.168.10.88:5000/list/lot/OLDER/NEW?search=test
http://192.168.10.88:5000/list/lot/OLDER/NEW
Another way to do what (I think) you are trying to do is use the query string for all your variables.
@bp.route('/list/')
@bp.route('/list/lot/')
@login_required
def index():
status = request.args.get('status', default=None)
time = request.args.get('time', default=None)
search = request.args.get('search', default=None)
print(search)
来源:https://stackoverflow.com/questions/64483400/python-routes-issues-using-flask