共用共同参数预处理的烧瓶路径

时间:2018-11-25 14:02:10

标签: python url flask 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"

共享与检查文件类型相同的代码。
我不想使用手动的文件类型检查方法,而是使用某种自动模式,该模式将首先运行路径的公共部分,然后再继续传递更大的路径“某些”或“其他”。 / p>

例如

# 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

是否可以为包含参数但也与其他元素分开的路径实现解决方案? 例如:要使上述预处理在<int:someothernumber>/<string:filetype>/<path:somepath>"上触发。

1 个答案:

答案 0 :(得分:0)

您在此域中有很多选择。

URL preprocessors运行得很早,

Flask通过以下示例指导您实现它们:

@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    g.lang_code = values.pop('lang_code', None)

来源:http://flask.pocoo.org/docs/1.0/patterns/urlprocessors/

要使用它来解决您的问题,我想我应该从以下内容开始:

@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    filetype = values.pop('filetype', None)
    if filetype == "bad":
        app.abort(404)
相关问题