Performance: Async views basics
This affects server response time and how quickly the browser receives the first byte, impacting page load speed.
Jump into concepts and practice - no test required
async def my_view(request): data = await slow_io_operation_async() return HttpResponse(data)
def my_view(request): data = slow_io_operation() return HttpResponse(data)
| Pattern | Server Blocking | Concurrency | Response Time | Verdict |
|---|---|---|---|---|
| Synchronous view with blocking I/O | High (blocks worker) | Low | Slower under load | [X] Bad |
| Async view with await on I/O | Low (non-blocking) | High | Faster under load | [OK] Good |
async views in Django?async def and can return a response directly.async def and returns a response. def my_view(request): return HttpResponse('Hello') is a normal sync view. async def my_view(request): await HttpResponse('Hello') wrongly uses await on a response object, which is not awaitable. def async my_view(request): return HttpResponse('Hello') has invalid syntax.from django.http import HttpResponse
import asyncio
async def my_view(request):
await asyncio.sleep(1)
return HttpResponse('Done')asyncio.sleep(1), which pauses for 1 second asynchronously before continuing.async def my_view(request):
response = HttpResponse('Hello')
await response
return responseimport httpx
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
return response.json()
async def my_view(request):
data = fetch_data()
return JsonResponse(data)data = await fetch_data() inside my_view to get the awaited result asynchronously.