python - 重写 Flask add_url_rule 以路由特定 URL

标签 python view flask django-class-based-views

我正在 Flask 中使用基于类的 View 来创建 CRUD REST API 并使用 add_url_rule 注册路由,如下所示...

class GenericAPI(MethodView):
    def get(self, item_group, item_id):
        ...
    def post(self, item_group, item_id):
        ...
    ...

api_view = GenericAPI.as_view('apps_api')
app.add_url_rule('/api/<item_group>', defaults={'item_id': None},
                 view_func=api_view, methods=['GET',])
app.add_url_rule('/api/<item_group>/<item_id>', 
                 view_func=api_view, methods=['GET',])
app.add_url_rule('/api/<item_group>/add', 
                 view_func=api_view, methods=['POST',])
app.add_url_rule('/api/<item_group>/<item_id>/edit', 
                 view_func=api_view, methods=['PUT',])
app.add_url_rule('/api/<item_group>/<item_id>/delete', 
                 view_func=api_view, methods=['DELETE',])

它处理基于item_group的特定数据库表和使用item_id的条目。因此,如果我有 /api/person,它将列出 person 表的条目。或者,如果我有 /api/equipment/2,它将检索设备表中 ID 为 2 的行。我有很多这样的任务,它们基本上都只需要 CRUD。

但是,如果我想在有其他 URL(例如 /api/analysis/summarize)时覆盖我的路由,理论上它会调用执行即时工作的函数,该怎么办?有没有办法做到这一点?

或者是将我的 URL 扩展到 /api/db/person/api/db/equipment/2 以执行一组操作和 的唯一方法/api/other_work_type 对于其他人?

最佳答案

可以正常注册/api/analysis/summarize。 Werkzeug/Flask 按复杂性(变量数量)对规则进行排序,首先采用最简单的路线。

例如:

@app.route('/api/foo')
def foo():
    return "Foo is special!"

@app.route('/api/<name>')
def generic(name):
    return "Hello %s!" % name

与您定义路由的顺序无关。

关于python - 重写 Flask add_url_rule 以路由特定 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17759563/

相关文章:

python - Flask 运行时出现问题

android - 将 TableRow 动态添加到 TableLayout 的上方

javascript - Flask: request.method = ='POST' 跳过 return 语句

python - Python-如何进行身份验证从AWS Lambda咨询Google Analytics(分析)?

python - 如何通读 CSV 然后在 Python 中发布批量 API 调用

MySql "view"、 "prepared statement"和 "Prepared statement needs to be re-prepared"

android - 如何在没有标签的情况下获取当前 View 寻呼机 View ?

jquery - 对 Flask 进行 ajax 调用时出现混合内容错误

python - 为什么 pyparsing 中的有序选择对于我的用例失败?

python - flask ,FlaskSocketIO - 运行时错误 : Cannot obtain socket from WSGI environment