When users upload files, their filenames might contain unsafe characters or paths. Secure filename handling makes sure these names are safe to use on your server.
Secure filename handling in Flask
from werkzeug.utils import secure_filename filename = secure_filename(user_uploaded_filename)
secure_filename cleans the filename by removing unsafe characters and paths.
It returns a safe version of the filename you can use to save files securely.
from werkzeug.utils import secure_filename filename = secure_filename('my photo.png') print(filename)
from werkzeug.utils import secure_filename filename = secure_filename('../../../etc/passwd') print(filename)
from werkzeug.utils import secure_filename filename = secure_filename('my*file?.txt') print(filename)
This Flask app accepts a file upload, secures the filename, and saves it safely to a folder.
It prevents unsafe filenames from causing problems on the server.
from flask import Flask, request from werkzeug.utils import secure_filename import os app = Flask(__name__) UPLOAD_FOLDER = '/tmp/uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return 'No file part', 400 file = request.files['file'] if file.filename == '': return 'No selected file', 400 filename = secure_filename(file.filename) save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(save_path) return f'File saved as {filename}' # To run this app, use: flask run # Then send a POST request with a file to /upload
Always use secure_filename before saving user-uploaded files.
Make sure the upload folder exists and has proper permissions.
Secure filenames help prevent overwriting important files and directory traversal attacks.
Use secure_filename to clean user-uploaded filenames.
This protects your server from unsafe file paths and characters.
It is a simple but important step in handling file uploads securely.
Practice
secure_filename in Flask when handling file uploads?Solution
Step 1: Understand the role of
This function cleans the filename by removing or replacing unsafe characters that could cause security issues.secure_filenameStep 2: Differentiate from other file handling tasks
It does not compress, encrypt, or randomly rename files; it only sanitizes the filename.Final Answer:
To clean the filename and remove unsafe characters -> Option AQuick Check:
Purpose of secure_filename = clean filename [OK]
- Thinking it encrypts or compresses files
- Assuming it renames files randomly
- Confusing filename cleaning with file content processing
secure_filename in a Flask app?Solution
Step 1: Identify the correct module for
The functionsecure_filenamesecure_filenameis provided bywerkzeug.utils, not directly by Flask.Step 2: Check import syntax
The correct syntax isfrom werkzeug.utils import secure_filename. Other options are either incorrect syntax or wrong modules.Final Answer:
from werkzeug.utils import secure_filename -> Option BQuick Check:
Import secure_filename = werkzeug.utils [OK]
- Importing directly from flask
- Using incorrect import syntax
- Trying to import as a module instead of function
from werkzeug.utils import secure_filename
filename = secure_filename('../../etc/passwd')Solution
Step 1: Understand how
The function removes directory traversal parts like '../' and replaces unsafe characters with underscores.secure_filenamehandles path traversalStep 2: Apply to '../../etc/passwd'
The '../' parts are removed and slashes replaced by underscores, resulting in 'etc_passwd'.Final Answer:
'etc_passwd' -> Option CQuick Check:
secure_filename('../../etc/passwd') = 'etc_passwd' [OK]
- Expecting original path to remain
- Thinking it returns only the basename
- Assuming it keeps dots or slashes
from 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'Solution
Step 1: Check imports
The code usesrequest.filesbut does not importrequestfrom Flask, causing a NameError.Step 2: Verify other parts
The filename is cleaned withsecure_filename, the method POST is correct, and folder existence is not checked but not an error here.Final Answer:
Missing import of request from flask -> Option AQuick Check:
request must be imported for request.files [OK]
- Forgetting to import request
- Assuming folder existence is automatically handled
- Confusing HTTP methods for uploads
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))Solution
Step 1: Check filename safety
Snippets usingsecure_filenamecorrectly clean the filename (eliminate the snippet using rawfile.filename).Step 2: Check file save path correctness
The correct snippet usesos.path.join(UPLOAD_FOLDER, filename)with the definedUPLOAD_FOLDERthat points inside the project 'uploads' folder. The remaining snippets use hardcoded paths like'/uploads/' + filenameoros.path.join('/uploads', filename), which may not save inside the project folder.Final Answer:
Use secure_filename and os.path.join with absolute UPLOAD_FOLDER path -> Option DQuick Check:
Safe filename + correct absolute path = Use secure_filename and os.path.join with absolute UPLOAD_FOLDER path [OK]
- Saving files with unsafe raw filenames
- Using hardcoded paths that may not exist
- Ignoring project directory structure
Ready to prove it?
Pass the test and this pattern moves unknown
