Bird
Raised Fist0
Flaskframework~20 mins

Allowed file types validation in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File Upload Validator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when uploading a .txt file?
Given this Flask code snippet that validates allowed file types, what will be the response if a user uploads a file named notes.txt?
Flask
from flask import Flask, request
app = Flask(__name__)

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files.get('file')
    if file and allowed_file(file.filename):
        return 'File accepted'
    else:
        return 'File type not allowed', 400
AFile type not allowed
BFile accepted
C500 Internal Server Error
DNo file uploaded
Attempts:
2 left
💡 Hint
Check the allowed extensions set and the file extension of the uploaded file.
📝 Syntax
intermediate
2:00remaining
Which option correctly checks allowed file extensions?
Which of the following functions correctly returns True only if the filename has an allowed extension from the set {'pdf', 'docx', 'txt'}?
A
def allowed_file(filename):
    return filename.split('.')[-1].lower() in {'pdf', 'docx', 'txt'}
B
}'txt' ,'xcod' ,'fdp'{ ni )(rewol.]1-[)'.'(tilps.emanelif nruter    
:)emanelif(elif_dewolla fed
C
def allowed_file(filename):
    return filename.endswith(('.pdf', '.docx', '.txt'))
D
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'pdf', 'docx', 'txt'}
Attempts:
2 left
💡 Hint
Consider case sensitivity and filenames without extensions.
🔧 Debug
advanced
2:00remaining
Why does this file validation always fail?
Consider this code snippet. Why does the file validation always reject files even if they have allowed extensions?
Flask
ALLOWED_EXTENSIONS = {'png', 'jpg'}

def allowed_file(filename):
    ext = filename.split('.')[-1]
    return ext in ALLOWED_EXTENSIONS

# Example usage:
print(allowed_file('image.PNG'))  # Returns False
ABecause the extension check is case sensitive and 'PNG' != 'png'
BBecause the split method is incorrect and does not get the extension
CBecause the allowed extensions set is empty
DBecause the function does not check if filename contains a dot
Attempts:
2 left
💡 Hint
Think about how string comparison works with uppercase and lowercase letters.
❓ state_output
advanced
2:00remaining
What is the value of result after running this code?
Given the following Flask helper function and usage, what is the value of result?
Flask
ALLOWED_EXTENSIONS = {'pdf', 'docx'}

def allowed_file(filename):
    if '.' not in filename:
        return False
    ext = filename.rsplit('.', 1)[1].lower()
    return ext in ALLOWED_EXTENSIONS

result = [allowed_file(f) for f in ['report.PDF', 'summary.docx', 'image.png', 'README']]
A[False, True, False, False]
B[True, True, True, False]
C[True, True, False, False]
D[False, False, False, False]
Attempts:
2 left
💡 Hint
Check extension case handling and filenames without extensions.
🧠 Conceptual
expert
3:00remaining
Which approach best prevents security risks in file uploads?
When validating allowed file types in Flask uploads, which approach best reduces security risks?
ACheck only the file extension from the filename string
BCheck the file extension and also verify the file's MIME type from the request
CAllow all file types and rely on server-side antivirus scanning
DRename the file to a random name without checking its type
Attempts:
2 left
💡 Hint
Think about how attackers can disguise file types.

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

  1. Step 1: Understand file upload risks

    Uploading files without validation can allow harmful files that may damage the server or application.
  2. Step 2: Purpose of allowed file types

    Checking allowed file types restricts uploads to safe, expected formats, reducing security risks.
  3. Final Answer:

    To ensure only safe and expected file formats are accepted -> Option D
  4. 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

  1. Step 1: Extract file extension correctly

    Splitting the filename by '.' and taking the last part gets the extension.
  2. Step 2: Check extension in allowed set

    Using 'in' checks if the extension is in the allowed_extensions set.
  3. Final Answer:

    if filename.split('.')[-1] in allowed_extensions: -> Option A
  4. 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

  1. Step 1: Extract extension from filename

    Splitting 'photo.png' by '.' gives ['photo', 'png'], last part is 'png'.
  2. Step 2: Check if extension is allowed

    'png' is in the set {'png', 'jpg'}, so condition is True and result is 'Allowed'.
  3. Final Answer:

    Allowed -> Option A
  4. 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

  1. Step 1: Understand the comparison

    The code compares a string (extension) to a set using '==', which is always False.
  2. Step 2: Correct way to check membership

    Use 'in' operator to check if extension is inside allowed_extensions set.
  3. Final Answer:

    Using '==' instead of 'in' to check extension -> Option C
  4. 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

  1. Step 1: Check for presence of extension

    Using '.' in filename ensures the file has an extension to avoid errors.
  2. 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.
  3. Step 3: Handle saving or rejecting file

    If extension is allowed, call save_file(), else reject_file().
  4. Final Answer:

    allowed = {'png', 'jpg', 'jpeg'} if '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed: save_file() else: reject_file() -> Option B
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard