python / expert
Snippet
Asynchronous Event Streaming with Django Async Generator Views
Django supports native async views. This example utilizes `StreamingHttpResponse` combined with an async generator to output real-time Server-Sent Events (SSE) efficiently while keeping client disconnections clean via `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
Breakdown
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:
Catches task cancellation when HTTP clients break connection early to perform necessary cleanup.
3
response = StreamingHttpResponse(self.event_stream(), content_type="text/event-stream")
Streams response chunk by chunk as emitted by the async generator using the text/event-stream content type.