Python 是否可以限制每个路由的数据大小?

Python 是否可以限制每个路由的数据大小?,python,python-3.x,flask,Python,Python 3.x,Flask,我知道可以在烧瓶中加入: app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 但我想确保一个特定的路由不会接受超过一定大小的POST数据 这可能吗?您需要检查具体路线本身的情况;您可以随时测试内容长度;是None或整数值: cl = request.content_length if cl is not None and cl > 3 * 1024 * 1024: abort(413) 在访问请求中的表单或文件数据之前执行此操

我知道可以在烧瓶中加入:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
但我想确保一个特定的路由不会接受超过一定大小的POST数据


这可能吗?

您需要检查具体路线本身的情况;您可以随时测试内容长度;是
None
或整数值:

cl = request.content_length
if cl is not None and cl > 3 * 1024 * 1024:
    abort(413)
在访问请求中的表单或文件数据之前执行此操作

您可以将其设置为视图的装饰器:

from functools import wraps
from flask import request, abort


def limit_content_length(max_length):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            cl = request.content_length
            if cl is not None and cl > max_length:
                abort(413)
            return f(*args, **kwargs)
        return wrapper
    return decorator
然后将其用作:

@app.route('/...')
@limit_content_length(3 * 1024 * 1024)
def your_view():
    # ...
这就是烧瓶的基本功能;当您尝试访问请求数据时,在尝试解析请求正文之前,首先检查内容长度头。使用decorator或手动检查,您只做了相同的测试,但在视图生命周期中稍早一点