python system_error ai_generated true

ResourceWarning: Unclosed transport <asyncio.sslproto._SSLProtocolTransport object>

ID: python/aiohttp-session-not-closed

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-05-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active

Root Cause

An aiohttp ClientSession is not properly closed, leaving underlying transport connections open.

generic

中文

aiohttp 的 ClientSession 未正确关闭,导致底层传输连接保持打开状态。

Workarounds

  1. 95% success Use async with for session lifecycle
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            data = await resp.text()
  2. 90% success Explicitly await session.close() in a finally block
    session = aiohttp.ClientSession()
    try:
        # use session
    finally:
        await session.close()

Dead Ends

Common approaches that don't work:

  1. Calling session.close() without awaiting it 80% fail

    session.close() is a coroutine; not awaiting it leaves the session unclosed.

  2. Relying on garbage collection to close the session 60% fail

    GC may not run immediately, and the warning appears due to delayed cleanup.