Concept Flow - Allowed file types validation
User uploads file
Check file extension
Accept file
Save file
End
The flow checks the uploaded file's extension. If allowed, it saves the file; otherwise, it rejects it with an error.
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
file = 'example.JPG'
result = allowed_file(file)| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Check if '.' in 'example.JPG' | True | Continue |
| 2 | Split 'example.JPG' by last '.' | ['example', 'JPG'] | Extension = 'JPG' |
| 3 | Convert extension to lowercase | 'jpg' | Extension = 'jpg' |
| 4 | Check if 'jpg' in ALLOWED_EXTENSIONS | True | File allowed |
| 5 | Return True from allowed_file | True |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| filename | 'example.JPG' | 'example.JPG' | 'example.JPG' | 'example.JPG' |
| extension | N/A | 'JPG' | 'jpg' | 'jpg' |
| allowed_file result | N/A | N/A | N/A | True |
Allowed file types validation in Flask: - Define ALLOWED_EXTENSIONS set with allowed suffixes - Check if filename contains '.' - Extract extension after last '.' and convert to lowercase - Return True if extension in allowed set, else False - Use this function to accept or reject uploaded files
photo.png and allowed_extensions = {'png', 'jpg'}?
filename = 'photo.png'
if filename.split('.')[-1] in allowed_extensions:
result = 'Allowed'
else:
result = 'Not Allowed'allowed_extensions = {'txt', 'pdf'}
filename = 'report.pdf'
if filename.split('.')[-1] == allowed_extensions:
print('File allowed')
else:
print('File not allowed')Pass the test and this pattern moves unknown