Think about when releasing the thread during waiting helps.
Async views help when the code waits on external I/O like APIs or databases, allowing other requests to run meanwhile. CPU-heavy or purely synchronous code won't benefit.
from django.http import JsonResponse import time async def my_view(request): time.sleep(2) # blocking call return JsonResponse({'status': 'done'})
Consider what happens when blocking code runs inside async functions.
Using blocking calls like time.sleep inside async views blocks the event loop, causing requests to be handled one after another, not concurrently.
async def get_user(request): user = await User.objects.get(id=1) return JsonResponse({'username': user.username})
Check if Django ORM methods are natively async or require wrappers.
Django ORM methods like get() are synchronous and must be wrapped with sync_to_async to be awaited in async views.
class SyncMiddleware: def __init__(self, get_response): self.get_response = get_response print('SyncMiddleware init') def __call__(self, request): print('SyncMiddleware before') response = self.get_response(request) print('SyncMiddleware after') return response class AsyncMiddleware: def __init__(self, get_response): self.get_response = get_response print('AsyncMiddleware init') async def __call__(self, request): print('AsyncMiddleware before') response = await self.get_response(request) print('AsyncMiddleware after') return response
Remember middleware __init__ runs on startup, __call__ runs per request in order.
Middleware __init__ runs in order on startup. On request, SyncMiddleware __call__ runs first, then calls AsyncMiddleware __call__, which awaits the next layer. The prints show nested calls accordingly.
from django.http import JsonResponse import asyncio async def slow_view(request): asyncio.sleep(3) return JsonResponse({'status': 'done'})
Check how to properly use async sleep functions.
asyncio.sleep is a coroutine that must be awaited. Without await, the coroutine is created but not run, causing the view to hang waiting indefinitely.