python / intermediate
Snippet
Asynchronous Server-Sent Events Streaming via StreamingHttpResponse
StreamingHttpResponse combined with asynchronous generator functions enables real-time event streaming without blocking worker threads. Setting the SSE text/event-stream content type streams updates continuously to client connections.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import asynciofrom django.http import StreamingHttpResponseasync def event_generator():for count in range(5):await asyncio.sleep(1)yield f"data: {{'step': {count}}}\n\n"async def sse_stream_view(request):response = StreamingHttpResponse(event_generator(),content_type='text/event-stream')response['Cache-Control'] = 'no-cache'return response
django
Breakdown
1
async def event_generator():
Defines an asynchronous generator that yields chunked text payload events over time.
2
yield f"data: {{'step': {count}}}\n\n"
Yields properly formatted Server-Sent Event text strings adhering to the SSE standard format.
3
response = StreamingHttpResponse(event_generator(), content_type='text/event-stream')
Wraps the generator inside Django's streaming response object configured for standard SSE streams.