python
runtime_error
ai_generated
true
RuntimeError: Event loop is closed
ID: python/starlette-event-loop-closed
80%Fix Rate
85%Confidence
0Evidence
2024-08-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
Root Cause
Async resources (e.g., aiohttp/httpx client, DB pool) created in one event loop are reused after that loop is closed, often across test cases or reloads.
generic中文
在某个事件循环中创建的异步资源(如 aiohttp/httpx 客户端、数据库连接池)在该循环关闭后被复用,常见于测试用例或热重载。
Workarounds
-
92% success
from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app): app.state.client = httpx.AsyncClient() yield await app.state.client.aclose() app = FastAPI(lifespan=lifespan) -
90% success
async with httpx.AsyncClient() as client: r = await client.get(url)
Dead Ends
Common approaches that don't work:
-
80% fail
Replaces loop but leaves stale client bound to old loop.
-
95% fail
Buffering setting irrelevant to event loop lifecycle.