python runtime_error ai_generated true

RuntimeError: Event loop is closed

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-11-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —
0.110+ active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 92% success
    @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% success
    Use httpx.AsyncClient with ASGITransport for tests to keep a single loop.

Dead Ends

Common approaches that don't work:

  1. 75% fail

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

  2. 70% fail

    Lifecycle bug remains; error recurs under TestClient.