Reputation: 495
I'm trying to write some wrapper function that would first check the size of the request and if the request size is larger than what I expected, a specific content would return to the client. I tried to use request.content_length
before, and it worked when the request is a POST
request, but can not work for a GET
request. Is there a way to do that?
Upvotes: 4
Views: 4773
Reputation: 104
A Flask Request inherits from werkzeug requests: http://werkzeug.pocoo.org/docs/0.12/quickstart/#enter-request. So the content length of a request in Flask is in its headers:flask.request.headers.get('Content-Length')
So you could do something like
import functools
def check_content_length_of_request_decorator(max_content_length):
def wrapper(fn):
@functools.wraps(fn)
def decorated_view(*args, **kwargs):
if int(flask.request.headers.get('Content-Length') or 0) > max_content_length:
return flask.abort(400, description='Too much content in request')
else:
return fn(*args, **kwargs)
return decorated_view
return wrapper
@app.route('/my_route', methods=['GET', 'POST'])
@check_content_length_of_request_decorator(1000)
def my_route():
return 'This request has a valid content length!'
Upvotes: 7