We want to add Server Side Events in our application, but currently the while True loop runs indefinitely and client disconnect is not causing the task to stop.
Reproducible example:
@api.get("/events")
async def get_events(request: ASGIRequest) -> StreamingHttpResponse:
async def generate_message() -> AsyncGenerator[str, None]:
while True:
await asyncio.sleep(1)
yield 'data: {"test": "testvalue"}nn'
print("Working...")
return StreamingHttpResponse(
generate_message(),
content_type="text/event-stream",
headers={
"X-Accel-Buffering": "no",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
)
Above example will print Working… until server is closed (even if client closes connection and is not receiving the data).
Any way to detect client disconnect to stop the while True loop?
Already tried to return simple HttpResponse, putting code in try..except, creating def close, async def close methods on StreamingHttpResponse.
- django-ninja==0.22.2
- django==4.2.13
- uvicorn[standard]==0.29.0
AlTosterino is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.