python - 不覆盖处理程序的路由层次结构

标签 python python-3.x flask quart

我正在编写一个 flask 应用程序。 拥有多个端点是有意义的,如下所示:

prefix + '/'
prefix + '/<id>'
prefix + '/<id>/parameters'
prefix + '/<id>/parameters/<param>'

但是,如果我尝试在蓝图中全部声明它们,则会收到 AssertionError: Handler is overwriting Existing for endpoint _blueprintname_._firsthandlername_

有什么办法可以解决这个问题吗?我知道以前在 .net core 等技术中已经直接完成了这一点。提前致谢。

最佳答案

如果您打算在 route 添加许多参数,您可以查看 this flask 模块。 它可以帮助您将路由分配给资源。

您可以按如下方式构建一组路由:

from flask import Flask, request
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

class Some(Resource):
  def get(self, id=None, params=None):
    """
      In order to allow empty params for routes, the named arguments
      must be initialized 
    """
    if id and params:
      return {'message':'this is get with id and params'}
    if id:
      return {'message':'this is get with id'}

    return {'message':'this is get'}


  def post():
    """
      One can use here reqparse module to validate post params
    """
    return {'message':'this is post'}

# Add the resource to the service 
api.add_resource(Some, '/', '/<string:id>','/<string:id>/<string:params>', ...)

# start the service
if __name__ == '__main__':
  app.run(debug=True)

关于python - 不覆盖处理程序的路由层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55322959/

相关文章:

python - Numpy:将每一行除以一个向量元素

python - StringIO 和与 'with' 语句的兼容性(上下文管理器)

python - 在Python中按文本列表中的值过滤

python - Python标准包将HTTP响应码转为文本消息

python - 如何使用 gridspec 调整列宽?

python - 如何在保存后停止 VScode 还原我的更改

python - 如何在 Python Pandas 中使用逗号作为小数分隔符的浮点格式?

html - 有时会显示登录表单,有时不会

python - 使用 Flask 将变量传递给所有 Jinja2 模板

python - Flask 上传权限被拒绝