python
runtime_error
ai_generated
true
RuntimeError: 事件循环已关闭
RuntimeError: Event loop is closed
ID: python/fastapi-asyncpg-event-loop-closed
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).
解决方案
-
92% 成功率
@asynccontextmanager async def lifespan(app): app.state.pool = await asyncpg.create_pool(dsn) yield await app.state.pool.close() app = FastAPI(lifespan=lifespan) -
85% 成功率
Use httpx.AsyncClient with ASGITransport for tests to keep a single loop.
无效尝试
常见但无效的做法:
-
75% 失败
Doesn't rebind existing pools; new loop still has no connections.
-
70% 失败
Lifecycle bug remains; error recurs under TestClient.