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
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.