python
network_error
ai_generated
true
asyncio.CancelledError: Task was cancelled during StreamingResponse iteration
ID: python/starlette-sse-client-disconnect
80%Fix Rate
83%Confidence
0Evidence
2024-11-26First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
Root Cause
An SSE StreamingResponse generator kept yielding after the client disconnected; the ASGI server cancelled the task.
generic中文
SSE StreamingResponse 生成器在客户端断开后继续 yield;ASGI 服务器取消了该任务。
Workarounds
-
90% success
async def gen(request: Request): while True: if await request.is_disconnected(): break yield f'data: {tick()}\n\n' await asyncio.sleep(1) -
85% success
async def gen(): try: while True: yield data await asyncio.sleep(1) finally: cleanup()
Dead Ends
Common approaches that don't work:
-
85% fail
The connection is gone; yield raises again and the task leaks.
-
70% fail
Clients still close tabs; cancellation is normal, not preventable.