What are Django async views and when do they actually improve performance? Django async व्यूज़ क्या हैं और ये वास्तव में परफॉर्मेंस को कब बेहतर बनाते हैं?
Since Django 3.1, views can be defined as async def functions, run under ASGI instead of WSGI, allowing a single worker to handle many concurrent requests without blocking on I/O — useful when a view spends most of its time waiting on network calls (external APIs, websockets) rather than doing CPU-bound work.
Async views provide no benefit, and can even hurt performance, for views dominated by synchronous ORM calls, since Django's ORM is still fundamentally synchronous (async ORM support is limited/newer) — calling the sync ORM from an async view requires wrapping it with sync_to_async, which reintroduces blocking. Async is most valuable for views that primarily fan out to multiple external APIs concurrently using asyncio.gather, not as a blanket performance upgrade for typical CRUD views.
import asyncio, httpx
async def aggregate_view(request):
async with httpx.AsyncClient() as client:
weather, news = await asyncio.gather(
client.get("https://api.weather.example/today"),
client.get("https://api.news.example/latest"),
)
return JsonResponse({"weather": weather.json(), "news": news.json()})Django 3.1 से, व्यूज़ को async def फंक्शन्स के रूप में डिफाइन किया जा सकता है, WSGI के बजाय ASGI के तहत चलाया जा सकता है, जिससे एक ही वर्कर I/O पर ब्लॉक हुए बिना कई समवर्ती रिक्वेस्ट्स को हैंडल कर सकता है।
सिंक्रोनस ORM कॉल्स पर हावी व्यूज़ के लिए async व्यूज़ कोई फायदा नहीं देते, और परफॉर्मेंस को नुकसान भी पहुँचा सकते हैं, क्योंकि Django का ORM अभी भी मूल रूप से सिंक्रोनस है।
async def aggregate_view(request):
async with httpx.AsyncClient() as client:
weather, news = await asyncio.gather(
client.get("https://api.weather.example/today"),
client.get("https://api.news.example/latest"),
)
return JsonResponse({"weather": weather.json(), "news": news.json()})Was this answer clear?