python runtime_error ai_generated true

RuntimeError: 事件循环已关闭

RuntimeError: Event loop is closed

ID: python/fastapi-event-loop-closed

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2025-01-22首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

在一个事件循环中创建的异步资源(httpx.AsyncClient、aiohttp session)在该循环关闭后被复用,常见于测试或重载场景。

English

Async resources (httpx.AsyncClient, aiohttp session) created in one event loop are reused after that loop closed, common in tests or reload.

generic

解决方案

  1. 90% 成功率
    Create clients inside lifespan and close on shutdown:
    @asynccontextmanager
    async def lifespan(app):
        app.state.client = httpx.AsyncClient()
        yield
        await app.state.client.aclose()
  2. 85% 成功率
    Use pytest-asyncio with a single loop fixture for tests.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Creates a fresh loop but existing clients bound to the old loop still fail.

  2. 80% 失败

    Subsequent requests hang or raise again on the closed loop.