python / intermediate
Snippet
Streaming Event Data in Django Async Views
Django supports asynchronous view functions and streaming responses. Yielding content from an async generator with StreamingHttpResponse allows sending Server-Sent Events (SSE) or long-running stream data without blocking server threads.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import asynciofrom typing import AsyncGeneratorfrom django.http import StreamingHttpResponse, HttpRequestasync def event_stream_generator() -> AsyncGenerator[str, None]:for i in range(1, 6):await asyncio.sleep(1)yield f"data: {{'event_id': {i}, 'status': 'processing'}}\n\n"async def async_event_stream(request: HttpRequest) -> StreamingHttpResponse:return StreamingHttpResponse(event_stream_generator(),content_type="text/event-stream")
django
Breakdown
1
async def event_stream_generator() -> AsyncGenerator[str, None]:
Defines an asynchronous generator function returning stream chunks sequentially.
2
await asyncio.sleep(1)
Asynchronously pauses execution without blocking the main event loop.
3
yield f"data: {{'event_id': {i}, 'status': 'processing'}}\n\n"
Yields a standard Server-Sent Event formatted string payload to the client.
4
return StreamingHttpResponse(
Returns a Django streaming HTTP response consuming the async generator chunk by chunk.
5
content_type="text/event-stream"
Sets the response header required for web browsers to handle Server-Sent Events.