python / expert
Snippet
Asynchronous StreamingHttpResponse using Generator Exception Propagation
Django supports async generator streaming responses. Utilizing asyncio.CancelledError inside an async generator allows clean resource reclamation when HTTP clients sever connections prematurely.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import asynciofrom typing import AsyncGeneratorfrom django.http import StreamingHttpResponseasync def generate_telemetry_stream() -> AsyncGenerator[str, None]:try:for step in range(5):await asyncio.sleep(0.1)yield f"event: metric\ndata: {{\"step\": {step}}}\n\n"except asyncio.CancelledError:# Clean up socket resources on client disconnectpassasync def telemetry_stream_view(request):return StreamingHttpResponse(generate_telemetry_stream(),content_type="text/event-stream")
django
Breakdown
1
async def generate_telemetry_stream() -> AsyncGenerator[str, None]:
Declares an asynchronous generator yielding data chunks without blocking the main event loop.
2
yield f"event: metric\ndata: {{\"step\": {step}}}\n\n"
Emits Server-Sent Event formatted string data to the downstream response stream.
3
except asyncio.CancelledError:
Catches cancellation signals triggered when client connection drops during streaming.