Python使用Flask路由问题 [英] Python Routes issues using Flask

查看:90
本文介绍了Python使用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': 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

我不明白为什么,打印总是返回None.

And I don't understand why, the print always return None.

有什么想法吗?

谢谢

推荐答案

如果要获取查询字符串,可以使用requestrequest.query_string:

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'

说明如何使用request来获取搜索值:request.args.get('search').

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'

网址看起来像这样:

http://192.168.10.88:5000/list/lot/parameters?time=OLDER&status=NEW&search=test

这篇关于Python使用Flask路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆