python
runtime_error
ai_generated
true
RuntimeError: Event loop is closed
ID: python/fastapi-asyncpg-event-loop-closed
80%Fix Rate
84%Confidence
0Evidence
2024-11-21First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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) -
85% success
Use httpx.AsyncClient with ASGITransport for tests to keep a single loop.
Dead Ends
Common approaches that don't work:
-
75% fail
Doesn't rebind existing pools; new loop still has no connections.
-
70% fail
Lifecycle bug remains; error recurs under TestClient.