notes.txt?from flask import Flask, request app = Flask(__name__) ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/upload', methods=['POST']) def upload_file(): file = request.files.get('file') if file and allowed_file(file.filename): return 'File accepted' else: return 'File type not allowed', 400
The allowed file types are only images with extensions png, jpg, jpeg, and gif. A .txt file is not in this set, so the function allowed_file returns False, leading to the 'File type not allowed' response with status 400.
Option D correctly checks if there is a dot in the filename and then extracts the extension safely using rsplit. It also converts the extension to lowercase to handle case variations.
Option D does not check if a dot exists and is case sensitive.
Option D uses endswith but this can cause false positives (e.g., 'filepdf').
Option D does not check if a dot exists and incorrectly handles filenames without extensions.
ALLOWED_EXTENSIONS = {'png', 'jpg'}
def allowed_file(filename):
ext = filename.split('.')[-1]
return ext in ALLOWED_EXTENSIONS
# Example usage:
print(allowed_file('image.PNG')) # Returns FalseThe function extracts the extension but does not convert it to lowercase before checking. Since 'PNG' (uppercase) is not equal to 'png' (lowercase), the check fails.
result after running this code?result?ALLOWED_EXTENSIONS = {'pdf', 'docx'}
def allowed_file(filename):
if '.' not in filename:
return False
ext = filename.rsplit('.', 1)[1].lower()
return ext in ALLOWED_EXTENSIONS
result = [allowed_file(f) for f in ['report.PDF', 'summary.docx', 'image.png', 'README']]'report.PDF' converts extension to lowercase 'pdf' which is allowed.
'summary.docx' is allowed.
'image.png' extension 'png' is not in allowed set.
'README' has no dot, so returns False.
Checking only the extension (A) is easy to bypass by renaming files.
Verifying MIME type (C) adds a layer of checking the actual content type sent by the browser.
Allowing all files (B) is risky even with antivirus.
Renaming files (D) helps avoid overwriting but does not prevent malicious content.