覆盖 Flask add_url_rule 以路由特定 URL [英] Overriding Flask add_url_rule to route a specific URL

查看:35
本文介绍了覆盖 Flask add_url_rule 以路由特定 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Flask 中使用基于类的视图来创建 CRUD REST API 并使用 add_url_rule 注册路由,就像这样......

I'm using the class-based views in Flask for creating a CRUD REST API and registering the routes using add_url_rule like so...

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.

It handles specific database tables based on item_group and entries using item_id. So if I have /api/person, it will list entries for the person table. Or if I have /api/equipment/2, it will retrieve the row with ID 2 in the equipment table. I have alot of these tasks and they all basically need CRUD only.

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

But what if I want to override my routing when I have some other URL like /api/analysis/summarize which theoretically would call to a function that does the on-the-fly work. Is there a way to do that?

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

Or is the only way extend my URLs to /api/db/person and /api/db/equipment/2 for one set of actions and /api/other_work_type for others?

推荐答案

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

You can register /api/analysis/summarize normally. Werkzeug/Flask sorts the rules by complexity (amount of variables), taking the simplest routes first.

例如:

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

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

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

Independent of the order you define the routes in.

这篇关于覆盖 Flask add_url_rule 以路由特定 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆