python - 不同参数的Python烧瓶蓝图注册路线
问题描述
我能够在调用 GET /category/category 时调用 route_category 方法,但在调用 GET /category/category?2 时无法调用 route_category_with_id;我观察到即使我调用 /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)
如何解决这个问题。提前致谢。
解决方案
您应该/可以将多个路由设置为单个方法
所以代码应该是这样的;
@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
推荐阅读
- graph-theory - 图中的总边数?
- python - Python Pandas 如果 df1.col 以(字符串)开头,使用该字符串创建 df2.col?
- google-cloud-platform - Pub/Sub 订购和多区域
- latex - 在 rmarkdown 中禁用 lmodern
- javascript - 未捕获的类型错误:无法读取 XMLHttpRequest.xhr.onload 处未定义的属性“url”
- android - 从 GET Method Retrofit Android 获取主键
- python - 是否可以在 Python 中将通用 C[T] 静态类型为 T ?
- node.js - 在 node.JS 串行上发送二进制文件
- python - 散景 CheckBoxGroupButton
- html - 允许子元素溢出,同时保持父元素的可滚动性