Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 want to ensure that one specific route will not accept POST data over a certain size.

Is this possible?

like image 571
Duke Dougal Avatar asked Jul 30 '14 12:07

Duke Dougal


1 Answers

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.

like image 76
Martijn Pieters Avatar answered Oct 11 '22 19:10

Martijn Pieters