How to detect client disconnects on StreamingHttpResponse (Server Side Events)? #2338
-
Hey! 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"}\n\n'
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? I'm not entirely sure if it's django-ninja==0.22.2 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
It's a |
Beta Was this translation helpful? Give feedback.
-
It's not |
Beta Was this translation helpful? Give feedback.
It's a
django-ninja
issue. Uvicorn sends thehttp.disconnect
event to the application as expected.