Is it possible to limit Flask POST data size on a per-route basis?

后端 未结 1 1471
感情败类
感情败类 2021-02-02 13:23

I am aware it is possible to set an overall limit on request size in Flask with:

app.config[\'MAX_CONTENT_LENGTH\'] = 16 * 1024 * 1024

BUT I wa

相关标签:
1条回答
  • 2021-02-02 13:50

    You'll need to check this for the specific route itself; you can always test the content length; request.content_length is either None or an integer value:

    cl = request.content_length
    if cl is not None and cl > 3 * 1024 * 1024:
        abort(413)
    

    Do this before accessing form or file data on the request.

    You can make this into a decorator for your views:

    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
    

    then use this as:

    @app.route('/...')
    @limit_content_length(3 * 1024 * 1024)
    def your_view():
        # ...
    

    This is essentially what Flask does; when you try to access request data, the Content-Length header is checked first before attempting to parse the request body. With the decorator or manual check you just made the same test, but a little earlier in the view lifecycle.

    0 讨论(0)
提交回复
热议问题