Challenge - 5 Problems
File Operations Mastery in Flask
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What happens when a Flask app saves an uploaded file?
Consider a Flask route that saves an uploaded file to the server. What is the main reason this operation is important in web apps?
Flask
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] file.save(f"uploads/{file.filename}") return 'File saved!'
Attempts:
2 left
💡 Hint
Think about why a web app might want to keep files users upload.
✗ Incorrect
Saving files on the server lets the app keep user data for future access or processing. The other options describe behaviors that don't happen automatically with file saving.
❓ state_output
intermediate2:00remaining
What is the output after reading a saved file in Flask?
Given this Flask code that reads a saved text file, what will be the output when accessing the route?
Flask
from flask import Flask app = Flask(__name__) @app.route('/read') def read_file(): with open('uploads/example.txt', 'r') as f: content = f.read() return content
Attempts:
2 left
💡 Hint
What does the Python open() function do when reading a file?
✗ Incorrect
The code opens the file in read mode and returns its full content as a string. Flask can serve this string as the HTTP response.
📝 Syntax
advanced2:00remaining
Identify the syntax error in this Flask file upload code
Which option contains the syntax error that will prevent the Flask app from saving an uploaded file?
Flask
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] file.save('uploads/' + file.filename) return 'Uploaded!'
Attempts:
2 left
💡 Hint
Look carefully at string concatenation syntax in Python.
✗ Incorrect
Option A is missing the '+' operator between the string and variable, causing a syntax error.
🔧 Debug
advanced2:00remaining
Why does this Flask file read code raise an error?
This Flask route tries to read a file but raises an error. What is the cause?
Flask
from flask import Flask app = Flask(__name__) @app.route('/read') def read_file(): with open('uploads/missing.txt', 'r') as f: content = f.read() return content
Attempts:
2 left
💡 Hint
Check if the file path exists on the server.
✗ Incorrect
Trying to open a non-existent file causes FileNotFoundError. The other errors do not apply here.
🧠 Conceptual
expert3:00remaining
Why must Flask apps handle file operations carefully?
Which reason best explains why file operations in Flask web apps require careful handling?
Attempts:
2 left
💡 Hint
Think about what could happen if users upload harmful files or overwrite server files.
✗ Incorrect
File operations can expose the server to security risks if not handled properly, such as overwriting critical files or accepting harmful content.