0
0
Djangoframework~8 mins

File upload handling basics in Django - Performance & Optimization

Choose your learning style9 modes available
Performance: File upload handling basics
MEDIUM IMPACT
This affects page load speed and interaction responsiveness by managing how files are received and processed on the server.
Handling file uploads in a Django web application
Django
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from asgiref.sync import sync_to_async
from django.http import HttpResponse

async def upload_file(request):
    if request.method == 'POST':
        file = request.FILES['file']
        await sync_to_async(default_storage.save)(file.name, ContentFile(file.read()))
        return HttpResponse('File uploaded asynchronously')
Using asynchronous file saving offloads blocking IO from the main thread, improving responsiveness.
📈 Performance GainNon-blocking file save reduces server response delay and improves INP.
Handling file uploads in a Django web application
Django
def upload_file(request):
    if request.method == 'POST':
        file = request.FILES['file']
        with open('/tmp/' + file.name, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)
        return HttpResponse('File uploaded')
Saving files synchronously in the request thread blocks the server, causing slow response and poor user experience.
📉 Performance CostBlocks server thread during file write, increasing response time and INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous file save in requestMinimal00[X] Bad
Asynchronous file save with async viewsMinimal00[OK] Good
Rendering Pipeline
File upload handling mainly affects server-side processing, which impacts the time before the server responds to the client, influencing interaction responsiveness.
Server Processing
Network Transfer
⚠️ BottleneckSynchronous file write blocks server thread, delaying response.
Core Web Vital Affected
INP
This affects page load speed and interaction responsiveness by managing how files are received and processed on the server.
Optimization Tips
1Avoid synchronous file writes in request handlers to prevent blocking.
2Use asynchronous or background processing for large file uploads.
3Monitor server response times during file uploads to ensure responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue with synchronous file uploads in Django?
AThey block the server thread, increasing response time.
BThey increase DOM reflows on the client.
CThey cause excessive CSS recalculations.
DThey add large JavaScript bundles.
DevTools: Network
How to check: Open DevTools, go to Network tab, upload a file, and observe the request duration and response time.
What to look for: Look for long request times indicating blocking server processing; shorter times indicate better performance.