覆盖Flask的add_url_rule以将特定URL路由到某个URL

2024-10-02 00:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Flask中基于类的视图来创建一个crudrestapi并使用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的行。我有很多这样的任务,他们基本上只需要积垢。在

但是,如果我想覆盖我的路由,当我有一些其他的URL,比如/api/analysis/summarize,理论上会调用一个执行动态工作的函数。有办法吗?在

或者,对于一组操作,将我的url扩展到/api/db/person和{},而对于其他操作,/api/other_work_type是唯一的方法吗?在


Tags: viewaddapiidappurl路由def
1条回答
网友
1楼 · 发布于 2024-10-02 00:31:47

您可以正常注册/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

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

相关问题 更多 >

    热门问题