Overriding Flask add_url_rule to route a specific URL

大憨熊 提交于 2019-12-13 16:03:19

问题


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',])

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.

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?

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?


回答1:


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

E.g.:

@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.



来源:https://stackoverflow.com/questions/17759563/overriding-flask-add-url-rule-to-route-a-specific-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!