Is it possible to limit Flask POST data size on a per-route basis?
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_lengthif 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 wrapsfrom flask import request, abortdef 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.