python system_error ai_generated true

资源警告:未关闭的传输对象

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

ID: python/aiohttp-session-not-closed

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率 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% 成功率 Explicitly await session.close() in a finally block
    session = aiohttp.ClientSession()
    try:
        # use session
    finally:
        await session.close()

无效尝试

常见但无效的做法:

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

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

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

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