📖 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
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
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
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
Hint
Use an if statement to check the file, then add comments inside and outside the block.
Practice
(1/5)
1. What is the main purpose of validating allowed file types in a Flask upload feature?
easy
A. To compress files before saving
B. To speed up the file upload process
C. To automatically rename files on upload
D. To ensure only safe and expected file formats are accepted
Solution
Step 1: Understand file upload risks
Uploading files without validation can allow harmful files that may damage the server or application.
To ensure only safe and expected file formats are accepted -> Option D
Quick Check:
Allowed file types = safety [OK]
Hint: Allowed types protect from unsafe uploads [OK]
Common Mistakes:
Thinking validation speeds upload
Confusing validation with renaming
Assuming validation compresses files
2. Which of the following is the correct way to check if a filename has an allowed extension in Flask?
easy
A. if filename.split('.')[-1] in allowed_extensions:
B. if filename.endswith(allowed_extensions):
C. if filename in allowed_extensions:
D. if allowed_extensions.contains(filename):
Solution
Step 1: Extract file extension correctly
Splitting the filename by '.' and taking the last part gets the extension.
Step 2: Check extension in allowed set
Using 'in' checks if the extension is in the allowed_extensions set.
Final Answer:
if filename.split('.')[-1] in allowed_extensions: -> Option A
Quick Check:
Split and check extension [OK]
Hint: Split filename by '.' and check last part [OK]
Common Mistakes:
Using endswith with a set (wrong syntax)
Checking whole filename in allowed extensions
Using non-existent 'contains' method
3. Given this Flask snippet, what will be the output if the uploaded file is named photo.png and allowed_extensions = {'png', 'jpg'}?
filename = 'photo.png'
if filename.split('.')[-1] in allowed_extensions:
result = 'Allowed'
else:
result = 'Not Allowed'
medium
A. Allowed
B. Not Allowed
C. Error: split method missing
D. Error: allowed_extensions undefined
Solution
Step 1: Extract extension from filename
Splitting 'photo.png' by '.' gives ['photo', 'png'], last part is 'png'.
Step 2: Check if extension is allowed
'png' is in the set {'png', 'jpg'}, so condition is True and result is 'Allowed'.
Final Answer:
Allowed -> Option A
Quick Check:
Extension 'png' in allowed set [OK]
Hint: Check last part after '.' in allowed set [OK]
Common Mistakes:
Confusing filename with extension
Assuming split returns error
Forgetting to define allowed_extensions
4. Identify the error in this Flask file validation code:
allowed_extensions = {'txt', 'pdf'}
filename = 'report.pdf'
if filename.split('.')[-1] == allowed_extensions:
print('File allowed')
else:
print('File not allowed')
medium
A. allowed_extensions should be a list, not a set
B. filename.split('.')[-1] is incorrect syntax
C. Using '==' instead of 'in' to check extension
D. Missing import for split function
Solution
Step 1: Understand the comparison
The code compares a string (extension) to a set using '==', which is always False.
Step 2: Correct way to check membership
Use 'in' operator to check if extension is inside allowed_extensions set.
Final Answer:
Using '==' instead of 'in' to check extension -> Option C
Quick Check:
Use 'in' for membership check [OK]
Hint: Use 'in' to check if extension is allowed [OK]
Common Mistakes:
Using '==' instead of 'in'
Thinking split needs import
Confusing set with list requirement
5. You want to allow only image files with extensions 'png', 'jpg', and 'jpeg' in your Flask app. Which code snippet correctly validates the uploaded file's extension and handles the case where the filename has no extension?
hard
A. allowed = {'png', 'jpg', 'jpeg'}
if filename.endswith(tuple(allowed)):
save_file()
else:
reject_file()
B. allowed = {'png', 'jpg', 'jpeg'}
if '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed:
save_file()
else:
reject_file()
C. allowed = ['png', 'jpg', 'jpeg']
if filename.split('.')[-1] in allowed:
save_file()
else:
reject_file()
D. allowed = {'png', 'jpg', 'jpeg'}
if filename.split('.')[1] in allowed:
save_file()
else:
reject_file()
Solution
Step 1: Check for presence of extension
Using '.' in filename ensures the file has an extension to avoid errors.
Step 2: Extract extension safely and check membership
Using rsplit('.', 1)[1].lower() gets the extension after the last dot, then checks if it's in allowed set.
Step 3: Handle saving or rejecting file
If extension is allowed, call save_file(), else reject_file().
Final Answer:
allowed = {'png', 'jpg', 'jpeg'}
if '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed:
save_file()
else:
reject_file() -> Option B
Quick Check:
Check dot, split once from right, then 'in' allowed [OK]
Hint: Check '.' then rsplit once, then 'in' allowed [OK]
Common Mistakes:
Not checking if filename has '.' before splitting
Using split without limit causing errors
Using endswith with tuple but missing case normalization
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.