Reputation: 27
Is it possible to do some shared preprocessing on routes when they share the same parameter?
I have the following two routes:
@app.route("/<string:filetype>/<int:number>/something", methods=['GET'])
def handle_get_file(filetype, number):
if filetype == "bad":
return status.HTTP_400_BAD_REQUEST
...some logic that has to do with "something"
@app.route("/<string:filetype>/someotherthing", methods=['GET'])
def handle_some_other_file(filetype):
if filetype == "bad":
return status.HTTP_400_BAD_REQUEST
...some logic that has to do with "some other thing"
that share the same code that checks for filetype.
Instead of manually calling for filetype check, I'd like to use some kind of automatic pattern, that will run the common part of the path first, before passing on to the greater routes "something" or "some other thing" further.
E.g
# this will match first
@app.route("/<string:filetype>/<path:somepath>")
def preprocessing(filetype):
if filetype == "bad":
return status.HTTP_400_BAD_REQUEST
else:
# process the rest of the route further
Is it possible to implement a solution for a path containing the parameter, but seperated with some other elements as well?
E.g: for the aforementioned preprocessing to trigger on <int:someothernumber>/<string:filetype>/<path:somepath>"
.
Upvotes: 2
Views: 730
Reputation: 4265
You have a lot of options in this domain.
URL preprocessors run very early,
Flask guides you through their implementation with this example:
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
g.lang_code = values.pop('lang_code', None)
Source: http://flask.pocoo.org/docs/1.0/patterns/urlprocessors/
To use this to solve your problem I guess I would therefore start with something like:
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
filetype = values.pop('filetype', None)
if filetype == "bad":
app.abort(404)
Upvotes: 1