python runtime_error ai_generated true

RuntimeError: Session is closed

ID: python/aiohttp-session-closed

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

Root Cause

An aiohttp.ClientSession was used after being closed, typically because it was created in an async with block that exited, or the session attribute was reused across requests after aclose().

generic

中文

aiohttp.ClientSession 在关闭后被使用,通常是因为其所在的 async with 块已退出,或在 aclose() 之后会话属性被跨请求复用。

Workarounds

  1. 90% success
    session = aiohttp.ClientSession()
    try:
        await session.get(url)
    finally:
        await session.close()
  2. 92% success
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            data = await resp.text()

Dead Ends

Common approaches that don't work:

  1. 70% fail

    The old session object is still closed; reassigning may leave background connectors attached to the closed session.

  2. 90% fail

    The session is closed, not slow; the request cannot even be queued.