app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024This limits uploads to 1MB.
What happens if a user tries to upload a 2MB file?
Flask automatically raises a RequestEntityTooLarge exception when the uploaded file size exceeds MAX_CONTENT_LENGTH. This results in a 413 HTTP error response.
Which code snippet correctly sets this limit?
The MAX_CONTENT_LENGTH config expects an integer number of bytes. 5MB is 5 times 1024 * 1024 bytes.
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
file.save('/tmp/' + file.filename)
return 'File saved'Users report uploading files larger than 2MB without errors.
What is the most likely reason?
Flask enforces MAX_CONTENT_LENGTH on the request size it receives. If a proxy or web server in front allows larger uploads, Flask may never see the limit exceeded.
request.content_length for a 3MB upload?What will
request.content_length contain?request.content_length returns the size of the request body in bytes, which for 3MB is 3 * 1024 * 1024 = 3145728 bytes.
Which approach correctly achieves this?
Flask lets you register an error handler for RequestEntityTooLarge that can return any response, including JSON with a 413 status.
