Bird
Raised Fist0
Flaskframework~20 mins

File uploads handling in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File Upload Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a file larger than the limit is uploaded?
Consider a Flask app configured with app.config['MAX_CONTENT_LENGTH'] = 1024 (1 KB). What will happen if a user tries to upload a file of 2 KB?
Flask
from flask import Flask, request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    return f"Received file: {file.filename}"
AThe server silently ignores the file and returns a 200 OK with no content.
BFlask raises a RequestEntityTooLarge exception and returns a 413 error automatically.
CThe file uploads successfully but is truncated to 1 KB.
DFlask saves the full file but logs a warning about the size.
Attempts:
2 left
💡 Hint
Think about what Flask does when the uploaded content exceeds the configured max size.
📝 Syntax
intermediate
2:00remaining
Which code correctly saves an uploaded file securely?
Given a Flask route handling file uploads, which option correctly saves the uploaded file using a secure 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']
    # Save file here
    pass
A
filename = secure_filename(file.filename)
file.save(f"uploads/{filename}")
return 'File saved'
B
filename = file.filename
file.save(f"uploads/{filename}")
return 'File saved'
C
filename = secure_filename(file.filename)
file.save(f"/uploads/{filename}")
return 'File saved'
D
filename = secure_filename(file.filename)
file.save(f"uploads/" + file.filename)
return 'File saved'
Attempts:
2 left
💡 Hint
Use the secure_filename function to avoid unsafe filenames.
🔧 Debug
advanced
2:00remaining
Why does this Flask upload code raise a KeyError?
This Flask route raises a KeyError when a POST request without a file is sent. Why?
Flask
from flask import Flask, request
app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    return f"Uploaded {file.filename}"
ABecause request.files is always empty regardless of the form.
BBecause the route does not allow GET method.
CBecause 'file' key is missing in request.files when no file is uploaded.
DBecause the file object does not have a filename attribute.
Attempts:
2 left
💡 Hint
Check what happens if the form does not include a file input named 'file'.
❓ state_output
advanced
2:00remaining
What is the value of 'filename' after this upload code runs?
Given this Flask code snippet, what will be the value of 'filename' if the uploaded file is named '../../secret.txt'?
Flask
from werkzeug.utils import secure_filename
filename = secure_filename('../../secret.txt')
A'secret_txt'
B'.._.._secret.txt'
C'../../secret.txt'
D'secret.txt'
Attempts:
2 left
💡 Hint
secure_filename removes directory traversal parts for safety.
🧠 Conceptual
expert
2:00remaining
Which statement about Flask file upload handling is true?
Select the correct statement about handling file uploads in Flask.
AThe request.files object contains FileStorage objects representing uploaded files.
BFlask automatically saves uploaded files to disk without calling save().
CYou must manually parse multipart form data to access uploaded files in Flask.
DFlask limits file upload size by default to 1 MB.
Attempts:
2 left
💡 Hint
Think about how Flask exposes uploaded files in the request object.

Practice

(1/5)
1. In Flask, which object do you use to access files uploaded by a user in a form?
easy
A. request.files
B. request.form
C. request.args
D. request.data

Solution

  1. Step 1: Understand Flask request objects

    Flask provides different objects to access data sent by the client. request.files holds uploaded files.
  2. Step 2: Identify correct object for file uploads

    Files sent via form with enctype='multipart/form-data' are accessed through request.files.
  3. Final Answer:

    request.files -> Option A
  4. Quick Check:

    File uploads = request.files [OK]
Hint: Uploaded files are in request.files, not request.form [OK]
Common Mistakes:
  • Using request.form to get files
  • Trying to access files via request.args
  • Not using multipart/form-data in form
2. Which of the following is the correct way to check if a file was uploaded before saving it in Flask?
easy
A. if request.args.get('file')
B. if request.files['file'] is None
C. if request.form['file'] != None
D. if 'file' in request.files and request.files['file'].filename != ''

Solution

  1. Step 1: Check file presence in request.files

    Use 'file' in request.files to confirm the file key exists.
  2. Step 2: Ensure filename is not empty

    Check request.files['file'].filename != '' to confirm a file was selected.
  3. Final Answer:

    if 'file' in request.files and request.files['file'].filename != '' -> Option D
  4. Quick Check:

    Check key and filename before saving [OK]
Hint: Check both key and filename before saving file [OK]
Common Mistakes:
  • Checking request.form instead of request.files
  • Not verifying filename is not empty
  • Using request.args for file data
3. What will be the output of this Flask route when a file named 'photo.png' is uploaded?
from flask import Flask, request
app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['file']
    filename = f.filename
    return f"Uploaded: {filename}"
medium
A. Uploaded: None
B. KeyError: 'file'
C. Uploaded: photo.png
D. Uploaded: ''

Solution

  1. Step 1: Access file from request.files

    The code gets the file object from request.files['file'], which holds the uploaded file.
  2. Step 2: Return the filename string

    The filename attribute contains the original file name, here 'photo.png', which is returned in the response.
  3. Final Answer:

    Uploaded: photo.png -> Option C
  4. Quick Check:

    Filename returned matches uploaded file [OK]
Hint: Filename attribute holds the uploaded file's name [OK]
Common Mistakes:
  • Assuming filename is None if file exists
  • Not using request.files to get file
  • Forgetting to use POST method
4. Identify the error in this Flask file upload code snippet:
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    if file.filename:
        file.save('/uploads/' + file.filename)
    return 'File saved'
medium
A. Using POST method instead of GET
B. Saving file without checking if 'file' key exists in request.files
C. Missing return statement
D. Incorrect filename attribute usage

Solution

  1. Step 1: Check for 'file' key in request.files

    The code accesses request.files['file'] directly without verifying if the key exists, risking a KeyError.
  2. Step 2: Properly check key before accessing

    Use if 'file' in request.files before accessing to avoid errors.
  3. Final Answer:

    Saving file without checking if 'file' key exists in request.files -> Option B
  4. Quick Check:

    Always check key exists before accessing [OK]
Hint: Check 'file' key in request.files before accessing [OK]
Common Mistakes:
  • Directly accessing request.files['file'] without check
  • Assuming filename always exists
  • Ignoring form enctype for file uploads
5. You want to securely save an uploaded file in Flask to a folder named 'uploads'. Which of the following is the best practice to avoid security risks?
hard
A. Use secure_filename() from werkzeug.utils before saving the file
B. Save the file directly with file.filename without changes
C. Rename the file to a fixed name like 'upload.txt' always
D. Save files outside the Flask app folder without any checks

Solution

  1. Step 1: Understand filename security risks

    Using raw filenames can allow directory traversal or unsafe characters causing security issues.
  2. Step 2: Use secure_filename() to sanitize filenames

    The secure_filename() function cleans the filename to a safe format before saving.
  3. Final Answer:

    Use secure_filename() from werkzeug.utils before saving the file -> Option A
  4. Quick Check:

    Sanitize filenames with secure_filename() [OK]
Hint: Always sanitize filenames with secure_filename() before saving [OK]
Common Mistakes:
  • Saving files with user-provided names directly
  • Ignoring filename sanitization
  • Using fixed names causing overwrites
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