python network_error ai_generated true

asyncio.CancelledError: StreamingResponse 迭代期间任务被取消

asyncio.CancelledError: Task was cancelled during StreamingResponse iteration

ID: python/starlette-sse-client-disconnect

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-11-26首次发现

版本兼容性

版本状态引入弃用备注
0.30+ active — — —

根因分析

SSE StreamingResponse 生成器在客户端断开后继续 yield;ASGI 服务器取消了该任务。

English

An SSE StreamingResponse generator kept yielding after the client disconnected; the ASGI server cancelled the task.

generic

解决方案

  1. 90% 成功率
    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% 成功率
    async def gen():
        try:
            while True:
                yield data
                await asyncio.sleep(1)
        finally:
            cleanup()

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 70% 失败

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