python runtime_error ai_generated true

RuntimeError: 无法写入正在关闭的传输

RuntimeError: Cannot write to closing transport

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

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

版本兼容性

版本状态引入弃用备注
3.8+ active
3.9+ active
3.10+ active
3.11+ active

根因分析

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

English

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

generic

解决方案

  1. 90% 成功率
    if request.transport is None or request.transport.is_closing():
        return
    await resp.write(chunk)
  2. 88% 成功率
    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()

无效尝试

常见但无效的做法:

  1. 70% 失败

    Silently drops data and may hide application logic bugs.

  2. 85% 失败

    The transport is already closing; timeout is unrelated.