B. Saving file without checking if 'file' key exists in request.files
C. Missing return statement
D. Incorrect filename attribute usage
Solution
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.
Step 2: Properly check key before accessing
Use if 'file' in request.files before accessing to avoid errors.
Final Answer:
Saving file without checking if 'file' key exists in request.files -> Option B
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
Step 1: Understand filename security risks
Using raw filenames can allow directory traversal or unsafe characters causing security issues.
Step 2: Use secure_filename() to sanitize filenames
The secure_filename() function cleans the filename to a safe format before saving.
Final Answer:
Use secure_filename() from werkzeug.utils before saving the file -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.