python / expert
Snippet
Django Async Views mit ASGI Simultaneous Datenbankoperationen
Dieses Snippet demonstriert Django Async Views mit ASGI für gleichzeitige Datenbankoperationen. Durch Wrapping von synchronen ORM-Aufrufen mit `@sync_to_async` und Verwendung von `asyncio.gather` werden mehrere Datenbankabfragen simultan statt sequenziell ausgeführt, was den Durchsatz für I/O-intensive Operationen drastisch verbessert. Dieses Pattern ist essentiell für performante Django-Endpunkte.
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
Erklärung
1
import asyncio
Importiert das asyncio-Modul für gleichzeitige Task-Verwaltung
2
from asgiref.sync import sync_to_async
Dekorator zum Wrappen von Sync-Funktionen für Async-Kontext-Ausführung
3
await asyncio.gather(...)
Führt mehrere Awaitables gleichzeitig aus und sammelt Ergebnisse oder behandelt Ausnahmen
4
@sync_to_async
Dekorator konvertiert synchrone ORM-Methoden zu async-kompatiblen Funktionen
5
with connection.cursor()
Direkter Datenbank-Cursor für rohe SQL-Ausführung im Async-Kontext