python
runtime_error
ai_generated
true
RuntimeError: Task got Future attached to a different loop
ID: python/fastapi-sync-endpoint-blocking
80%Fix Rate
84%Confidence
0Evidence
2024-08-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
在 FastAPI 的同步端点中使用了异步库或跨线程操作,导致事件循环冲突。
generic中文
在 FastAPI 的同步端点中使用了异步库或跨线程操作,导致事件循环冲突。
Workarounds
-
85% success
from starlette.concurrency import run_in_threadpool; result = await run_in_threadpool(sync_func)
-
95% success
async def endpoint(): await async_func()
Dead Ends
Common approaches that don't work:
-
30% fail
如果库是同步的,会阻塞事件循环,但不会导致此错误。
-
90% fail
线程和事件循环不兼容,导致 Future 跨循环。