python / expert
Snippet
Django Async Views with ASGI Concurrent Database Operations
This snippet demonstrates Django async views leveraging ASGI for concurrent database operations. By wrapping sync ORM calls with `@sync_to_async` and using `asyncio.gather`, multiple database queries execute simultaneously instead of sequentially, dramatically improving throughput for I/O-bound operations. The pattern is essential for building high-performance Django endpoints that handle multiple external API calls or complex database aggregations.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import asynciofrom asgiref.sync import sync_to_asyncfrom django.http import JsonResponsefrom django.db import connectionclass AsyncDjangoView:async def get(self, request):results = await asyncio.gather(self.fetch_users(),self.fetch_products(),self.fetch_orders(),return_exceptions=True)return JsonResponse({'users': results[0],'products': results[1],'orders': results[2]})@sync_to_asyncdef fetch_users(self):with connection.cursor() as cursor:cursor.execute('SELECT id, name FROM auth_user LIMIT 100')return cursor.fetchall()@sync_to_asyncdef fetch_products(self):from myapp.models import Productreturn list(Product.objects.filter(is_active=True)[:100].values('id', 'name'))@sync_to_asyncdef fetch_orders(self):from myapp.models import Orderreturn list(Order.objects.select_related('user').only('id', 'total', 'user__name')[:100])
django
Breakdown
1
import asyncio
Imports the asyncio module for concurrent task management
2
from asgiref.sync import sync_to_async
Provides decorator to wrap sync functions for async context execution
3
await asyncio.gather(...)
Executes multiple awaitables concurrently, collecting results or handling exceptions
4
@sync_to_async
Decorator converts sync ORM methods to async-compatible functions
5
with connection.cursor()
Direct database cursor for raw SQL execution in async context