Performance: Secure filename handling
This affects page load speed and security by preventing unsafe file paths that can cause server errors or delays.
from werkzeug.utils import secure_filename filename = secure_filename(request.files['file'].filename) request.files['file'].save(os.path.join(UPLOAD_FOLDER, filename))
filename = request.files['file'].filename request.files['file'].save(os.path.join(UPLOAD_FOLDER, filename))
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct user filename usage | 0 (server-side) | 0 | 0 | [X] Bad |
| Using secure_filename() | 0 (server-side) | 0 | 0 | [OK] Good |
secure_filename in Flask when handling file uploads?secure_filenamesecure_filename in a Flask app?secure_filenamesecure_filename is provided by werkzeug.utils, not directly by Flask.from werkzeug.utils import secure_filename. Other options are either incorrect syntax or wrong modules.from werkzeug.utils import secure_filename
filename = secure_filename('../../etc/passwd')secure_filename handles path traversalfrom werkzeug.utils import secure_filename
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = secure_filename(file.filename)
file.save('/uploads/' + filename)
return 'File saved'request.files but does not import request from Flask, causing a NameError.secure_filename, the method POST is correct, and folder existence is not checked but not an error here.file is from request.files?
from werkzeug.utils import secure_filename
import os
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'uploads')
# Which snippet below is correct?
A) filename = secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER, filename))
B) filename = file.filename
file.save(os.path.join(UPLOAD_FOLDER, filename))
C) filename = secure_filename(file.filename)
file.save('/uploads/' + filename)
D) filename = secure_filename(file.filename)
file.save(os.path.join('/uploads', filename))secure_filename correctly clean the filename (eliminate the snippet using raw file.filename).os.path.join(UPLOAD_FOLDER, filename) with the defined UPLOAD_FOLDER that points inside the project 'uploads' folder. The remaining snippets use hardcoded paths like '/uploads/' + filename or os.path.join('/uploads', filename), which may not save inside the project folder.Pass the test and this pattern moves unknown