我能够在调用GET / category / category时调用route_category方法,但是我无法在调用GET / category / category时调用route_category_with_id?2;我观察到,即使您调用/ category / category / 2,我也总是会进入route_category方法。我们该如何解决?
我声明了蓝图的Python初始化文件
from flask import Blueprint
blueprint = Blueprint(
'category_blueprint',
__name__,
url_prefix='/category',
template_folder='templates',
static_folder='static'
)
并且我有下面声明的类别的routes.py文件
@blueprint.route('/<template>', methods=["GET", "POST"])
def route_category(template):
do_something
@blueprint.route('/<template>/<int:id>', methods=["GET"])
def route_category_with_id(template):
do_something_with_id
routes.py在python主程序中注册如下
module = import_module('category.routes'.format(module_name))
app.register_blueprint(module.blueprint)
如何解决此问题。预先感谢。
答案 0 :(得分:0)
您应该/可以将多个路由设置为一种方法
所以代码应该像这样;
@blueprint.route('/<template>', methods=["GET", "POST"])
@blueprint.route('/<template>/<int:id>', methods=["GET"])
def route_category(template, id=None):
if id is None:
# do_something
pass
else:
# do_something_with_id
pass
答案 1 :(得分:0)
请求args (request.args)与路由variables不同。
意思是route_category_with_id
正在寻找:
http://<ip-address>/category/2
要保留?2
语法,您需要将其转换为?key=value
,并使用request.args.get('key')
在视图中访问它
答案 2 :(得分:0)
以下情况应该使您清楚明白
:http://example.com/category
时,它会调用route_category
方法。http://example.com/category?2
时,它会调用route_category
,查询字符串由2
组成。 ?
之后的内容称为查询字符串-您可以使用flask.request.args
在Flask中访问它。看起来应该像?key=value
,然后是flask.request.args.get("key")
http://example.com/category/2
->时,它才会调用route_category_with_id
,因为您在此处传递了route参数。