问题
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