Complete the code to set the maximum allowed file size to 2 megabytes in a Flask app.
app.config['MAX_CONTENT_LENGTH'] = [1]
The MAX_CONTENT_LENGTH config expects the size in bytes. 2 megabytes equals 2 * 1024 * 1024 bytes.
Complete the code to handle the error when a user uploads a file larger than the limit in Flask.
@app.errorhandler([1]) def handle_file_too_large(e): return 'File too large', 413
Flask raises RequestEntityTooLarge exception when the file size exceeds the limit. This is used in the error handler decorator.
Fix the error in the code to correctly limit file size and handle errors in Flask.
from flask import Flask, request from werkzeug.exceptions import [1] app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 @app.errorhandler(RequestEntityTooLarge) def file_too_large(e): return 'File too big', 413
The correct exception to import from werkzeug.exceptions is RequestEntityTooLarge. Other names are invalid and cause import errors.
Fill both blanks to create a Flask route that rejects files larger than 500 KB and returns a custom message.
app.config['MAX_CONTENT_LENGTH'] = [1] @app.errorhandler([2]) def too_large(e): return 'File is too large!', 413
The max size is set to 500 KB in bytes (500 * 1024). The error handler uses the RequestEntityTooLarge exception.
Fill all three blanks to create a Flask app that limits upload size to 3 MB, handles the error, and returns a JSON response.
from flask import Flask, jsonify from werkzeug.exceptions import [1] app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = [2] @app.errorhandler(RequestEntityTooLarge) def handle_large_file(e): return jsonify({'error': 'File too large'}), [3]
The exception imported is RequestEntityTooLarge. The max size is 3 MB in bytes (3 * 1024 * 1024). The HTTP status code for payload too large is 413.