首页 > 解决方案 > 不同参数的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)

如何解决这个问题。提前致谢。

标签: pythonflask

解决方案


您应该/可以将多个路由设置为单个方法

所以代码应该是这样的;

@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

推荐阅读