不同参数的Python flask蓝图注册路线

时间:2019-05-21 08:15:50

标签: python flask

我能够在调用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)

如何解决此问题。预先感谢。

3 个答案:

答案 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)

以下情况应该使您清楚明白

  1. 调用http://example.com/category时,它会调用route_category方法。
  2. 调用http://example.com/category?2时,它会调用route_category,查询字符串由2组成。 ?之后的内容称为查询字符串-您可以使用flask.request.args在Flask中访问它。看起来应该像?key=value,然后是flask.request.args.get("key")
  3. 仅当您调用http://example.com/category/2->时,它才会调用route_category_with_id,因为您在此处传递了route参数。
相关问题