0
0
Flaskframework~8 mins

Allowed file types validation in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Allowed file types validation
MEDIUM IMPACT
This affects page load speed and user interaction responsiveness by preventing unnecessary file uploads and server processing.
Validating uploaded file types to prevent invalid files
Flask
from flask import request
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

file = request.files['file']
if file and allowed_file(file.filename):
    file.save('/uploads/' + file.filename)
else:
    return 'Invalid file type', 400
Checks file extension before saving, preventing unnecessary server processing of invalid files.
📈 Performance GainReduces server workload and response blocking, improving INP and overall user experience
Validating uploaded file types to prevent invalid files
Flask
from flask import request

file = request.files['file']
# No validation on file type
file.save('/uploads/' + file.filename)
No file type check causes server to process all files, including invalid or malicious ones.
📉 Performance CostBlocks server processing for all uploads, increasing response time and INP delays
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No file type validationN/AN/AN/A[X] Bad
Early file type validation on serverN/AN/AN/A[OK] Good
Rendering Pipeline
File type validation happens on the server before file processing and response generation, reducing server-side blocking and improving interaction responsiveness.
Server Processing
Response Generation
⚠️ BottleneckServer Processing when handling invalid files
Core Web Vital Affected
INP
This affects page load speed and user interaction responsiveness by preventing unnecessary file uploads and server processing.
Optimization Tips
1Always validate file types early on the server to avoid unnecessary processing.
2Reject invalid files quickly to reduce server response blocking and improve interaction speed.
3Use a whitelist of allowed extensions to keep validation simple and fast.
Performance Quiz - 3 Questions
Test your performance knowledge
Why does validating allowed file types on the server improve performance?
AIt increases the number of files uploaded, improving throughput.
BIt prevents processing invalid files, reducing server load and response time.
CIt delays the file upload to allow more user input.
DIt reduces the size of the uploaded files automatically.
DevTools: Network
How to check: Upload files with allowed and disallowed types and observe server responses in the Network panel.
What to look for: Look for 400 errors on invalid files and faster response times on rejected uploads indicating good validation.