Bird
Raised Fist0
Flaskframework~20 mins

Secure filename handling in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Secure Filename Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Flask code output when uploading a file named '../../secret.txt'?

Consider this Flask snippet that uses secure_filename from werkzeug.utils to sanitize uploaded filenames.

from flask import Flask, request
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    return filename

If a user uploads a file named ../../secret.txt, what will be the returned filename?

Flask
from flask import Flask, request
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    return filename
Asecret-txt
B../../secret.txt
Csecret_txt
Dsecret.txt
Attempts:
2 left
💡 Hint

Think about how secure_filename removes directory paths and unsafe characters.

📝 Syntax
intermediate
1:30remaining
Which option correctly imports and uses secure_filename in Flask?

You want to safely handle uploaded filenames in Flask. Which code snippet correctly imports and uses secure_filename?

A
from werkzeug.utils import secure_filename
filename = secure_filename(uploaded_file.filename)
B
from flask.utils import secure_filename
filename = secure_filename(uploaded_file.filename)
C
from werkzeug import secure_filename
filename = secure_filename(uploaded_file.filename)
D
import werkzeug
filename = werkzeug.utils.secure_filename(uploaded_file.filename)
Attempts:
2 left
💡 Hint

Check the correct module path for secure_filename in modern Flask/Werkzeug.

🔧 Debug
advanced
2:30remaining
Why does this Flask upload code raise a FileNotFoundError when saving?

Look at this Flask route that saves an uploaded file:

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(filename)
    return 'Saved'

Sometimes this raises FileNotFoundError. Why?

Flask
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(filename)
    return 'Saved'
AThe file object is closed before save is called.
Bsecure_filename returns None, causing save to fail.
CThe current directory may not exist or be writable, so saving without a full path fails.
DFlask requires an absolute path for file.save, relative paths are disallowed.
Attempts:
2 left
💡 Hint

Think about where the file is saved and if that location exists.

❓ state_output
advanced
2:00remaining
What is the value of filename after this code runs?

Given this code snippet:

from werkzeug.utils import secure_filename

original = 'my..file...name.tar.gz'
filename = secure_filename(original)

What is the value of filename?

Flask
from werkzeug.utils import secure_filename

original = 'my..file...name.tar.gz'
filename = secure_filename(original)
Amy.file.name.tar.gz
Bmy..file...name.tar.gz
Cmy-file-name.tar.gz
Dmy_file_name_tar_gz
Attempts:
2 left
💡 Hint

Consider how secure_filename handles multiple dots and special characters.

🧠 Conceptual
expert
1:30remaining
Why is using secure_filename important in Flask file uploads?

Which of the following best explains why using secure_filename is critical when handling uploaded files in Flask?

AIt validates the file content type to prevent malware.
BIt prevents directory traversal attacks by removing path separators and unsafe characters from filenames.
CIt encrypts the filename to protect user privacy.
DIt compresses the file to save storage space.
Attempts:
2 left
💡 Hint

Think about what risks come from unsafe filenames in uploads.

Practice

(1/5)
1. What is the main purpose of using secure_filename in Flask when handling file uploads?
easy
A. To clean the filename and remove unsafe characters
B. To compress the uploaded file
C. To encrypt the file contents
D. To rename the file to a random string

Solution

  1. Step 1: Understand the role of secure_filename

    This function cleans the filename by removing or replacing unsafe characters that could cause security issues.
  2. Step 2: Differentiate from other file handling tasks

    It does not compress, encrypt, or randomly rename files; it only sanitizes the filename.
  3. Final Answer:

    To clean the filename and remove unsafe characters -> Option A
  4. Quick Check:

    Purpose of secure_filename = clean filename [OK]
Hint: Remember: secure_filename cleans names, not file content [OK]
Common Mistakes:
  • Thinking it encrypts or compresses files
  • Assuming it renames files randomly
  • Confusing filename cleaning with file content processing
2. Which of the following is the correct way to import secure_filename in a Flask app?
easy
A. from flask import secure_filename
B. from werkzeug.utils import secure_filename
C. import secure_filename from flask
D. import werkzeug.secure_filename

Solution

  1. Step 1: Identify the correct module for secure_filename

    The function secure_filename is provided by werkzeug.utils, not directly by Flask.
  2. Step 2: Check import syntax

    The correct syntax is from werkzeug.utils import secure_filename. Other options are either incorrect syntax or wrong modules.
  3. Final Answer:

    from werkzeug.utils import secure_filename -> Option B
  4. Quick Check:

    Import secure_filename = werkzeug.utils [OK]
Hint: Import secure_filename from werkzeug.utils, not flask [OK]
Common Mistakes:
  • Importing directly from flask
  • Using incorrect import syntax
  • Trying to import as a module instead of function
3. What will be the output of the following code snippet?
from werkzeug.utils import secure_filename
filename = secure_filename('../../etc/passwd')
medium
A. 'passwd'
B. '.._.._etc_passwd'
C. 'etc_passwd'
D. '../../etc/passwd'

Solution

  1. Step 1: Understand how secure_filename handles path traversal

    The function removes directory traversal parts like '../' and replaces unsafe characters with underscores.
  2. Step 2: Apply to '../../etc/passwd'

    The '../' parts are removed and slashes replaced by underscores, resulting in 'etc_passwd'.
  3. Final Answer:

    'etc_passwd' -> Option C
  4. Quick Check:

    secure_filename('../../etc/passwd') = 'etc_passwd' [OK]
Hint: secure_filename removes ../ and replaces slashes with underscores [OK]
Common Mistakes:
  • Expecting original path to remain
  • Thinking it returns only the basename
  • Assuming it keeps dots or slashes
4. Identify the error in this Flask file upload snippet:
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'
medium
A. Missing import of request from flask
B. Using insecure filename without cleaning
C. Saving file without checking if upload folder exists
D. Incorrect HTTP method for file upload

Solution

  1. Step 1: Check imports

    The code uses request.files but does not import request from Flask, causing a NameError.
  2. Step 2: Verify other parts

    The filename is cleaned with secure_filename, the method POST is correct, and folder existence is not checked but not an error here.
  3. Final Answer:

    Missing import of request from flask -> Option A
  4. Quick Check:

    request must be imported for request.files [OK]
Hint: Always import request when accessing request.files [OK]
Common Mistakes:
  • Forgetting to import request
  • Assuming folder existence is automatically handled
  • Confusing HTTP methods for uploads
5. You want to save uploaded files securely in Flask, ensuring filenames are safe and files are saved inside a folder named 'uploads' inside your project. Which code snippet correctly handles this, assuming 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))
hard
A. Use secure_filename but join with absolute string '/uploads' ignoring project path
B. Use raw filename without cleaning and os.path.join with absolute path
C. Use secure_filename but save with hardcoded relative path string
D. Use secure_filename and os.path.join with absolute UPLOAD_FOLDER path

Solution

  1. Step 1: Check filename safety

    Snippets using secure_filename correctly clean the filename (eliminate the snippet using raw file.filename).
  2. Step 2: Check file save path correctness

    The correct snippet uses os.path.join(UPLOAD_FOLDER, filename) with the defined UPLOAD_FOLDER that points inside the project 'uploads' folder. The remaining snippets use hardcoded paths like '/uploads/' + filename or os.path.join('/uploads', filename), which may not save inside the project folder.
  3. Final Answer:

    Use secure_filename and os.path.join with absolute UPLOAD_FOLDER path -> Option D
  4. Quick Check:

    Safe filename + correct absolute path = Use secure_filename and os.path.join with absolute UPLOAD_FOLDER path [OK]
Hint: Always combine secure_filename with os.path.join and absolute folder path [OK]
Common Mistakes:
  • Saving files with unsafe raw filenames
  • Using hardcoded paths that may not exist
  • Ignoring project directory structure
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