Complete the code to define allowed file extensions as a set.
ALLOWED_EXTENSIONS = [1]Allowed file extensions should be stored in a set for fast lookup.
Complete the function to check if a filename has an allowed extension.
def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].[1]() in ALLOWED_EXTENSIONS
startswith or endswith instead of lower.We convert the extension to lowercase before checking to allow case-insensitive matching.
Fix the error in the file upload route to validate file type correctly.
from flask import request, redirect, url_for @app.route('/upload', methods=['POST']) def upload_file(): file = request.files.get('file') if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], [1])) return redirect(url_for('uploaded_file', filename=filename)) return 'Invalid file type', 400
file.filename directly without securing it.file or request.filename which are incorrect.The variable filename holds the safe filename to save.
Fill both blanks to create a dictionary comprehension filtering allowed files and mapping to their extensions.
files = ['image.png', 'doc.pdf', 'photo.jpg'] allowed_files = {f: f.[1]('.', 1)[1].[2]() for f in files if '.' in f and f.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS}
split instead of rsplit may cause wrong splits.upper instead of lower causes mismatch with allowed extensions.Use rsplit to split from the right and lower to normalize extension case.
Fill all three blanks to define a Flask route that accepts file uploads and validates allowed types.
@app.route('/upload', methods=[[1]]) def upload(): file = request.files.get('file') if file and allowed_file(file.[2]): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], [3])) return 'File uploaded successfully' return 'Invalid file type', 400
file.filename.The route must accept POST requests. The filename attribute is accessed as file.filename. The variable filename is used to save the file.