413 REQUEST ENTITY TOO LARGE flask werkzeug gunicorn MAX_CONTENT_LENGTH

100 Views Asked by At

I am using flask in combination with werkzeug and gunicorn.

I am running Gunicorn with the following command:

gunicorn --log-level debug --timeout 300 --limit-request-line 0 --limit-request-field_size 0 --workers 1 -b 0.0.0.0:80 app:app

In app.py I have the following setting

app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024

and I have a webpage with a form that has a table with 2000 rows that I want to submit.

The total size of the request body is 800 KB.

Still the server just terminates the connection on form submit with

413 REQUEST ENTITY TOO LARGE

I tried different configurations of flask environment variables

FLASK_ENV=production
FLASK_DEBUG=0

or

FLASK_ENV=development
FLASK_DEBUG=1

No matter what configuration I do, I get always the same 413 status.

Any suggestion?

1

There are 1 best solutions below

0
Nima Mazloumi On

Turned out the issue was with the Flask Request class. It has a limit hardcoded for max_form_parts. We had to subclass it to increase the limit.

The better approach is to avoid large form fields and instead post a JSON. I will do that but thanks to Justin Triplett the following workaround worked:

import flask
from flask import Request


class CustomRequest(Request):
    def __init__(self, *args, **kwargs):
        super(CustomRequest, self).__init__(*args, **kwargs)
        self.max_form_parts = 2000


app = flask.Flask(__name__)
app.request_class = CustomRequest


@app.route("/")
def index_view():
    greeting = "Hello, World!"
    return flask.render_template("index.html", greeting=greeting)


if __name__ == "__main__":
    app.run()