python runtime_error ai_generated true

RuntimeError: 事件循环已关闭

RuntimeError: Event loop is closed

ID: python/fastapi-asyncpg-event-loop-closed

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

版本兼容性

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

根因分析

asyncpg/httpx 客户端在导入时于 lifespan 之外创建;连接池绑定到已关闭的事件循环(常见于 TestClient)。

English

asyncpg/httpx client created at import time outside lifespan; connection pool bound to a loop that has since closed (common with TestClient).

generic

解决方案

  1. 92% 成功率
    @asynccontextmanager
    async def lifespan(app):
        app.state.pool = await asyncpg.create_pool(dsn)
        yield
        await app.state.pool.close()
    app = FastAPI(lifespan=lifespan)
  2. 85% 成功率
    Use httpx.AsyncClient with ASGITransport for tests to keep a single loop.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Doesn't rebind existing pools; new loop still has no connections.

  2. 70% 失败

    Lifecycle bug remains; error recurs under TestClient.