0
0
Flaskframework~30 mins

Secure filename handling in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Secure filename handling in Flask
📖 Scenario: You are building a simple Flask web app that allows users to upload files. To keep the app safe, you need to make sure the filenames are handled securely so no harmful files or paths can cause problems.
🎯 Goal: Create a Flask app that accepts a file upload and saves the file using a secure filename.
📋 What You'll Learn
Create a Flask app instance named app
Create a route /upload that accepts POST requests
Use werkzeug.utils.secure_filename to sanitize the uploaded file's name
Save the uploaded file to a folder named uploads using the secure filename
💡 Why This Matters
🌍 Real World
Web apps often let users upload files. Handling filenames securely prevents attackers from overwriting important files or uploading dangerous files.
💼 Career
Knowing how to safely handle file uploads is important for backend web developers to protect applications from security risks.
Progress0 / 4 steps
1
Set up Flask app and upload folder
Create a Flask app instance called app and set the configuration variable UPLOAD_FOLDER to the string 'uploads'.
Flask
Need a hint?

Use Flask(__name__) to create the app. Set app.config['UPLOAD_FOLDER'] to 'uploads'.

2
Import secure_filename and create upload route
Import secure_filename from werkzeug.utils. Create a route /upload that accepts POST requests and defines a function upload_file.
Flask
Need a hint?

Import secure_filename. Use @app.route('/upload', methods=['POST']) to create the route.

3
Get file from request and secure filename
Inside the upload_file function, get the file from request.files['file']. Use secure_filename on the file's filename and save it to a variable called filename.
Flask
Need a hint?

Use file = request.files['file'] to get the file. Then use filename = secure_filename(file.filename).

4
Save the file using secure filename
Save the uploaded file to the folder app.config['UPLOAD_FOLDER'] joined with filename using file.save(). Use os.path.join to combine the folder and filename. Import os at the top.
Flask
Need a hint?

Import os. Use file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) to save the file.