python runtime_error ai_generated true

RuntimeError: 会话已关闭

RuntimeError: Session is closed

ID: python/aiohttp-session-outside-context

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

版本兼容性

版本状态引入弃用备注
3.9+ active — — —

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率
    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% 成功率
    session = aiohttp.ClientSession()
    try:
        async with session.get(url) as r:
            ...
    finally:
        await session.close()

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 95% 失败

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