python network_error ai_generated true

anyio.ClosedResourceError: ClosedResourceError

ID: python/starlette-streaming-response-disconnect

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.30.x active — — —
0.36.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Does not prevent mid-stream client disconnects.

  2. 85% fail

    Channel is closed; further sends raise again.