python / expert
Snippet
Asynchrones Event-Streaming mit Django Async Generator Views
Django unterstützt native asynchrone Views. Dieses Beispiel nutzt `StreamingHttpResponse` zusammen mit einem asynchronen Generator zur Echtzeit-Ausgabe von Server-Sent Events (SSE) und behandelt Verbindungsabbrüche mittels `asyncio.CancelledError`.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import asynciofrom typing import AsyncGeneratorfrom django.http import StreamingHttpResponsefrom django.views import Viewclass ServerSentEventsView(View):async def event_stream(self) -> AsyncGenerator[str, None]:try:for i in range(10):await asyncio.sleep(1)yield f"data: {{\"event_id\": {i}, \"status\": \"processing\"}}\n\n"yield "data: {\"status\": \"complete\"}\n\n"except asyncio.CancelledError:# Handle client disconnect gracefullypassasync def get(self, request, *args, **kwargs):response = StreamingHttpResponse(self.event_stream(),content_type="text/event-stream")response["Cache-Control"] = "no-cache"response["X-Accel-Buffering"] = "no"return response
django
Erklärung
1
async def event_stream(self) -> AsyncGenerator[str, None]:
Defines an async generator function producing SSE formatted data strings without blocking worker threads.
2
except asyncio.CancelledError:
Fängt den Aufgabenabbruch ab, wenn der HTTP-Client die Verbindung vorzeitig trennt, um Ressourcen freizugeben.
3
response = StreamingHttpResponse(self.event_stream(), content_type="text/event-stream")
Streamt die Antwort stückweise vom asynchronen Generator mit dem Content-Type text/event-stream.