python runtime_error ai_generated true

RuntimeError: 事件循环已关闭。

RuntimeError: Event loop is closed

ID: python/starlette-event-loop-closed

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

版本兼容性

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

根因分析

在某个事件循环中创建的异步资源(如 aiohttp/httpx 客户端、数据库连接池)在该循环关闭后被复用,常见于测试用例或热重载。

English

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

解决方案

  1. 92% 成功率
    from contextlib import asynccontextmanager
    @asynccontextmanager
    async def lifespan(app):
        app.state.client = httpx.AsyncClient()
        yield
        await app.state.client.aclose()
    app = FastAPI(lifespan=lifespan)
  2. 90% 成功率
    async with httpx.AsyncClient() as client:
        r = await client.get(url)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Replaces loop but leaves stale client bound to old loop.

  2. 95% 失败

    Buffering setting irrelevant to event loop lifecycle.