0
0
Flaskframework~8 mins

Serving uploaded files in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Serving uploaded files
MEDIUM IMPACT
This affects page load speed and responsiveness when users request uploaded files from the server.
Serving uploaded files to users
Flask
from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/uploads/<filename>')
def serve_file(filename):
    return send_from_directory('uploads', filename, as_attachment=False)
send_from_directory streams files with conditional responses enabled by default, avoiding full file transfers when cached, improving response time and reducing server load.
📈 Performance Gainefficient streaming with conditional checks, enables 304 responses, reduces bandwidth and faster responses for large or repeated requests
Serving uploaded files to users
Flask
from flask import Flask, send_file
app = Flask(__name__)

@app.route('/uploads/<filename>')
def serve_file(filename):
    return send_file(f'uploads/{filename}')
Using send_file directly on large files blocks the server process during transfer and lacks conditional responses by default, causing slow response times for large or repeated requests.
📉 Performance Costblocks server process during file transfer, always sends full file even if cached by client
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
send_file with large files0 (server-side)00[X] Bad
send_from_directory streaming0 (server-side)00[OK] Good
Rendering Pipeline
When a user requests an uploaded file, the server reads the file and sends it over the network. Efficient file serving reduces server processing time and network delays, speeding up the browser's ability to display or download the file.
Server File I/O
Network Transfer
Browser Rendering
⚠️ BottleneckServer File I/O blocking the worker process during transfers
Core Web Vital Affected
LCP
This affects page load speed and responsiveness when users request uploaded files from the server.
Optimization Tips
1Avoid blocking the server unnecessarily when serving uploaded files.
2Use streaming methods like send_from_directory for efficient file delivery.
3Monitor network transfer times to ensure fast file loading.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is using send_file directly on large uploaded files in Flask a performance concern?
AIt blocks the server process during file transfer without conditional checks.
BIt causes the browser to reflow the page multiple times.
CIt increases the CSS selector complexity.
DIt delays JavaScript execution on the client.
DevTools: Network
How to check: Open DevTools, go to Network tab, request the uploaded file URL, and observe the file transfer time and size.
What to look for: Look for fast response start time and steady data transfer without delays indicating efficient file serving.