0
0
Flaskframework~30 mins

Allowed file types validation in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Allowed file types validation
📖 Scenario: You are building a simple Flask web app that lets users upload files. To keep the app safe and clean, you want to allow only certain file types like images.
🎯 Goal: Create a Flask app that accepts file uploads but only allows files with extensions .png, .jpg, and .jpeg. If a user tries to upload a file with a different extension, the app should reject it.
📋 What You'll Learn
Create a set called ALLOWED_EXTENSIONS with the values 'png', 'jpg', and 'jpeg'.
Write a function called allowed_file(filename) that returns True if the file extension is in ALLOWED_EXTENSIONS, otherwise False.
Use Flask's request.files to get the uploaded file with the key 'file'.
Check if the uploaded file is allowed using allowed_file() before saving or processing.
💡 Why This Matters
🌍 Real World
Web apps often need to accept user files but must restrict file types to avoid security risks and keep data clean.
💼 Career
Validating file uploads is a common task for web developers working with Flask or other web frameworks.
Progress0 / 4 steps
1
Create the allowed file types set
Create a set called ALLOWED_EXTENSIONS with these exact strings: 'png', 'jpg', and 'jpeg'.
Flask
Need a hint?

Use curly braces {} to create a set with the given strings.

2
Write the allowed_file function
Write a function called allowed_file(filename) that returns True if the file extension after the last dot in filename is in ALLOWED_EXTENSIONS, otherwise returns False. Use filename.rsplit('.', 1) to split the extension.
Flask
Need a hint?

Check if there is a dot in the filename, then get the extension after the last dot and convert it to lowercase before checking.

3
Get the uploaded file from the request
Use request.files['file'] to get the uploaded file from the Flask request object. Assign it to a variable called file.
Flask
Need a hint?

Use Flask's request.files dictionary with the key 'file' to get the uploaded file.

4
Check if the file is allowed before processing
Write an if statement that uses allowed_file(file.filename) to check if the uploaded file is allowed. Inside the if, add a comment # process the file. Outside the if, add a comment # reject the file.
Flask
Need a hint?

Use an if statement to check the file, then add comments inside and outside the block.