python network_error ai_generated true

anyio.ClosedResourceError: 资源已关闭错误

anyio.ClosedResourceError: ClosedResourceError

ID: python/starlette-streaming-response-disconnect

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

版本兼容性

版本状态引入弃用备注
0.30.x active — — —
0.36.x active — — —

根因分析

客户端在StreamingResponse仍在向ASGI发送通道写入时断开连接。

English

Client disconnected while a StreamingResponse was still writing to the ASGI send channel.

generic

解决方案

  1. 90% 成功率
    async for chunk in gen():\n    if await request.is_disconnected():\n        break\n    yield chunk
  2. 88% 成功率
    try:\n    yield data\nexcept anyio.ClosedResourceError:\n    return

无效尝试

常见但无效的做法:

  1. 80% 失败

    Does not prevent mid-stream client disconnects.

  2. 85% 失败

    Channel is closed; further sends raise again.