Consider this Flask snippet that uses secure_filename from werkzeug.utils to sanitize uploaded filenames.
from flask import Flask, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = secure_filename(file.filename)
return filenameIf a user uploads a file named ../../secret.txt, what will be the returned filename?
from flask import Flask, request from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = secure_filename(file.filename) return filename
Think about how secure_filename removes directory paths and unsafe characters.
The secure_filename function strips directory components and returns only the base filename, removing dangerous path parts like ../. So '../../secret.txt' becomes 'secret.txt'.
You want to safely handle uploaded filenames in Flask. Which code snippet correctly imports and uses secure_filename?
Check the correct module path for secure_filename in modern Flask/Werkzeug.
The correct import is from werkzeug.utils. Other options either import from wrong modules or use incorrect syntax.
Look at this Flask route that saves an uploaded file:
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = secure_filename(file.filename)
file.save(filename)
return 'Saved'Sometimes this raises FileNotFoundError. Why?
@app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = secure_filename(file.filename) file.save(filename) return 'Saved'
Think about where the file is saved and if that location exists.
Calling file.save(filename) saves to the current working directory. If that directory doesn't exist or isn't writable, a FileNotFoundError occurs. The fix is to specify a valid directory path that exists and is writable.
Given this code snippet:
from werkzeug.utils import secure_filename original = 'my..file...name.tar.gz' filename = secure_filename(original)
What is the value of filename?
from werkzeug.utils import secure_filename original = 'my..file...name.tar.gz' filename = secure_filename(original)
Consider how secure_filename handles multiple dots and special characters.
secure_filename replaces multiple dots with single dots except for the extension separator. It keeps dots in the filename but removes unsafe characters. So 'my..file...name.tar.gz' becomes 'my.file.name.tar.gz'.
Which of the following best explains why using secure_filename is critical when handling uploaded files in Flask?
Think about what risks come from unsafe filenames in uploads.
secure_filename sanitizes filenames to prevent attackers from using paths like '../../' to overwrite files or access unauthorized locations. It does not encrypt, compress, or validate file content.