Consider this Flask route that handles file uploads. What will the response be if a user uploads a file named example.txt?
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): file = request.files.get('file') if file: filename = file.filename return f'File {filename} uploaded successfully' return 'No file uploaded'
Check how the file is accessed from the request and what attribute is used for the filename.
The request.files.get('file') retrieves the uploaded file object. If it exists, file.filename returns the original filename. So the response includes the uploaded filename.
Given a Flask route receiving a file upload, which code snippet correctly saves the file to the uploads/ folder?
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): file = request.files.get('file') if file: # Save file here pass return 'No file uploaded'
Look for the method provided by Flask's FileStorage object to save files.
The save() method is the correct way to save an uploaded file to disk in Flask. Other methods like write or store do not exist on the file object.
Examine this Flask route snippet. Why does it raise a KeyError when no file is uploaded?
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] if file: return f'Uploaded {file.filename}' return 'No file uploaded'
Consider how dictionary access works in Python when a key is missing.
Accessing request.files['file'] directly raises a KeyError if the key 'file' is not present. Using request.files.get('file') avoids this error by returning None instead.
filename after this Flask upload code runs?Given this Flask route, what will be the value of filename if the user uploads a file named photo.png?
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): file = request.files.get('file') filename = file.filename if file else 'No file' return filename
Check the conditional expression assigning filename.
If a file is uploaded, file is not None, so filename is set to file.filename, which is the uploaded file's name.
When building a Flask app that accepts file uploads, which configuration helps prevent security risks by limiting the size of uploaded files?
Think about how to limit the size of incoming data to avoid large file uploads.
The MAX_CONTENT_LENGTH setting limits the maximum size of incoming request data, preventing users from uploading files larger than the specified size. Other options configure upload folder, debugging, or security keys but do not limit upload size.