Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the content length of a GET request in flask

Tags:

request

flask

get

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?

like image 978
Wang Nick Avatar asked Sep 12 '25 06:09

Wang Nick


1 Answers

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!'

like image 192
Peter Van 't Zand Avatar answered Sep 15 '25 03:09

Peter Van 't Zand