FastAPI升级至0.115.4后遇RuntimeError: generator didn't stop问题求助
FastAPI升级后出现RuntimeError: generator didn't stop的解决方法
这个错误源于同步数据库依赖生成器在异步端点中的生命周期处理问题,FastAPI 0.115.x版本对同步依赖的线程池执行逻辑做了调整,你的get_db函数中的异常捕获块干扰了生成器的正常终止流程。
方案1:移除冗余的异常捕获块
你的get_db函数中的except块属于冗余逻辑,FastAPI会自动将端点中抛出的异常向上传播,无需手动捕获再重新抛出。修改后的代码如下:
def get_db() -> Generator[SQLServer, None, None]: # coverage: omit try: db = SessionLocal() yield db finally: db.close() print(f'Closing the database connection')
原理说明
当端点使用数据库连接时发生异常,会直接传递到yield语句处,随后finally块会执行连接关闭操作,生成器能正常走完整个生命周期,不会出现未终止的情况。
方案2:将同步依赖包装为异步依赖(可选)
如果需要保留异常打印逻辑,或者希望更明确地处理同步依赖在异步环境中的执行,可以将get_db包装为异步函数,借助FastAPI的线程池工具:
from fastapi.concurrency import contextmanager_in_threadpool import inspect def _get_sync_db() -> Generator[SQLServer, None, None]: try: db = SessionLocal() yield db except Exception as e: print(f'Error : raised from {inspect.stack()[0][3]} - {str(e)}') raise finally: db.close() print(f'Closing the database connection') async def get_db(): async with contextmanager_in_threadpool(_get_sync_db) as db: yield db
修改后保持端点中db: SQLServer = Depends(get_db)的引用即可。
额外修复点
原端点代码存在两处语法/逻辑问题:
- 路径参数
{activity_id}未在函数参数中定义(当前参数为param_1) - 函数定义末尾缺少右括号
修正后的端点代码:
@router.get('/{activity_id}') async def get_activity_detail(activity_id: int, response: Response, creds: Creds = Depends(), db: SQLServer = Depends(get_db)): # 业务逻辑
内容的提问来源于stack exchange,提问作者Hussain
相关产品推荐
相关产品推荐

