python runtime_error ai_generated true

RuntimeError: Cannot write to closing transport

ID: python/aiohttp-cannot-write-after-response-started

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8+ active
3.9+ active
3.10+ active
3.11+ active

Root Cause

aiohttp server tried to write to a StreamResponse after the client disconnected or the response was already finalized.

generic

中文

客户端断开或响应已完成后,aiohttp 服务器仍尝试向 StreamResponse 写入数据。

Workarounds

  1. 90% success
    if request.transport is None or request.transport.is_closing():
        return
    await resp.write(chunk)
  2. 88% success
    resp = web.StreamResponse()
    await resp.prepare(request)
    try:
        async for chunk in source:
            await resp.write(chunk)
    except (ConnectionResetError, RuntimeError):
        pass
    finally:
        await resp.write_eof()

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Silently drops data and may hide application logic bugs.

  2. 85% fail

    The transport is already closing; timeout is unrelated.