Reputation: 111
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?
Upvotes: 4
Views: 1388
Reputation: 1
Improper setting of the parameters MAX_CONTENT_LENGTH, MAX_FORM_MEMORY_SIZE, and MAX_FORM_PARTS can lead to the “413 Request Entity Too Large” error. enter image description here
Upvotes: 0
Reputation: 624
There are several settings in nginx, gunicorn and flask that govern this behavior, what worked for me was:
flask
MEGABYTE = (2 ** 10) ** 2
app.config['MAX_CONTENT_LENGTH'] = None
# Max number of fields in a multi part form (I don't send more than one file)
# app.config['MAX_FORM_PARTS'] = ...
app.config['MAX_FORM_MEMORY_SIZE'] = 50 * MEGABYTE
Gunicorn:
--limit-request-line 0
Nginx: (Could be either server block, or route block (per route basis)
client_max_body_size 50M;
Upvotes: 1
Reputation: 111
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()
Upvotes: 4