Skip to content Skip to sidebar Skip to footer

Python Routes Issues Using Flask

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

Solution 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_requireddefindex(status, time, search):
    print(request.query_string, request.args.get('search'), time, status)
    #  b'search=test' test OLDER NEWreturn'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

Solution 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)

Post a Comment for "Python Routes Issues Using Flask"