python network_error ai_generated true

asyncio.CancelledError: Task was cancelled during StreamingResponse iteration

ID: python/starlette-sse-client-disconnect

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-11-26First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 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)
  2. 85% success
    async def gen():
        try:
            while True:
                yield data
                await asyncio.sleep(1)
        finally:
            cleanup()

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The connection is gone; yield raises again and the task leaks.

  2. 70% fail

    Clients still close tabs; cancellation is normal, not preventable.