共享公共参数的路由预处理

2024-04-20 00:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文

当路由共享同一参数时,是否可以对其进行共享预处理?
我有以下两条路线:

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

与检查文件类型的代码相同。
我不想手动调用文件类型检查,而是想使用某种自动模式,首先运行路径的公共部分,然后再进一步传递到更大的路由“something”或“something”。你知道吗

例如

# 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>"上触发。你知道吗


Tags: apphttp路由stringreturnifrequestdef
1条回答
网友
1楼 · 发布于 2024-04-20 00:39:16

在这个领域你有很多选择。你知道吗

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)

相关问题 更多 >