python runtime_error ai_generated true

RuntimeError: Session is closed

ID: python/aiohttp-session-outside-context

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9+ active — — —

Root Cause

An aiohttp.ClientSession was used after exiting its async with block (which calls close()), or after session.close() was awaited.

generic

中文

在退出 async with 块(会调用 close())之后,或在 await session.close() 之后,仍使用了 aiohttp.ClientSession。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The context manager closes the session on exit; reusing it always raises.

  2. 95% fail

    Closed sessions cannot issue new requests; the connector is shut down.