Managing Request Body Constraints
To protect your application from denial-of-service attacks or resource exhaustion, you can enforce limits on the size and complexity of incoming request bodies. This is managed through global configuration or by modifying the flask.wrappers.Request object directly.
Configuring Global Limits
You can set application-wide limits using the Flask.config dictionary. These limits apply to every request unless specifically overridden.
from flask import Flask
app = Flask(__name__)
# Limit the total request body size to 16 Megabytes
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
# Limit individual non-file form fields to 100 Kilobytes (default is 500,000 bytes)
app.config["MAX_FORM_MEMORY_SIZE"] = 100_000
# Limit the number of parts in a multipart form to 50 (default is 1,000)
app.config["MAX_FORM_PARTS"] = 50
Overriding Limits for Specific Views
If you have specific routes that require larger payloads (like a file upload endpoint) or stricter limits, you can override the global configuration by setting properties on the request object within the view function.
from flask import Flask, request
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1 * 1024 * 1024 # 1MB global limit
@app.post("/upload")
def upload_large_file():
# Increase the limit to 100MB for this specific request
request.max_content_length = 100 * 1024 * 1024
# Accessing form or files will now respect the new limit
file = request.files["archive"]
return "Upload successful"
@app.post("/strict-data")
def strict_view():
# Tighten the limit for a specific sensitive endpoint
request.max_content_length = 1024 # 1KB
return "Data received"
Handling Limit Violations
When a request exceeds any of these constraints, Flask (via Werkzeug) raises a 413 RequestEntityTooLarge error. You can catch this globally using an error handler to provide a custom response.
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(413)
def request_entity_too_large(error):
return "The uploaded file is too large. Maximum allowed size is 16MB.", 413
Available Constraints
The Request object in this project supports three primary constraint properties, which fall back to the corresponding application configuration:
| Property | Config Key | Default | Description |
|---|---|---|---|
max_content_length | MAX_CONTENT_LENGTH | None | Total bytes read from the request stream. |
max_form_memory_size | MAX_FORM_MEMORY_SIZE | 500,000 | Max size (bytes) of any non-file field in multipart/form-data. |
max_form_parts | MAX_FORM_PARTS | 1,000 | Max number of fields/parts in multipart/form-data. |
Troubleshooting and Gotchas
Infinite Streams
If MAX_CONTENT_LENGTH is set to None (the default) and the incoming request does not provide a Content-Length header, Flask may refuse to read the data to prevent potential infinite streams, unless the WSGI server explicitly indicates the stream terminates.
Lazy Parsing
Constraints are typically enforced when the request data is first accessed (e.g., calling request.form, request.files, or request.get_json()). If your view function never accesses the request body, the 413 error might not be triggered even if the payload is oversized.
Per-Request Timing
When overriding limits in a view, ensure you set the property before accessing any data attributes like request.form. Once the data has been parsed using the old limits, changing the property will have no effect on the already-processed body.