python / intermediate
Snippet
Streaming Real-Time Data with Asynchronous Generators in Django Views
Django supports streaming asynchronous responses using async generator functions passed into StreamingHttpResponse. This pattern maintains open connections without blocking server worker threads during real-time data push operations such as Server-Sent Events (SSE).
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
import asynciofrom django.http import StreamingHttpResponseasync def event_stream_generator():for i in range(1, 6):await asyncio.sleep(1)yield f"data: Event payload {i}\n\n"async def async_sse_view(request):return StreamingHttpResponse(event_stream_generator(),content_type="text/event-stream")
django
Breakdown
1
async def event_stream_generator():
Defines an asynchronous generator function yielding data chunks periodically.
2
await asyncio.sleep(1)
Asynchronously pauses execution without blocking the event loop.
3
yield f"data: Event payload {i}\n\n"
Yields formatted Server-Sent Event data strings to the stream buffer.
4
return StreamingHttpResponse(
Instantiates a streaming response passing the async iterator and SSE header content type.