You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中Depends传参报错:对象不可调用问题求助

FastAPI Depends传递参数触发TypeError的解决方法

问题原因

你直接调用database.get_db(string_here="string")时,该函数执行后返回的是生成器对象(从错误提示<generator object get_db at ...>可确认),而FastAPI的Depends()要求接收一个可调用对象(比如函数本身),而非函数执行后的结果,因此抛出“不是可调用对象”的错误。

解决方法

以下三种方案均可解决该问题:

方法1:用lambda函数包装

在Depends()中传入lambda函数,由lambda负责调用带参数的get_db:

@router.post("/post")
async def post_request(
    db: Session = Depends(lambda: database.get_db(string_here="string"))
):
    return ...

方法2:使用functools.partial绑定参数

借助functools.partial预先绑定参数,生成一个可调用的偏函数:

from functools import partial

@router.post("/post")
async def post_request(
    db: Session = Depends(partial(database.get_db, string_here="string"))
):
    return ...

方法3:重构get_db为闭包形式

若需多次复用带参数的数据库连接,可将get_db改为闭包结构,先接收参数再返回生成器函数:

# 数据库文件代码修改:
def get_db(string_here: str):
    def db_generator():
        # 原get_db逻辑示例:
        db = SessionLocal()
        try:
            # 可在此使用传入的string_here参数
            yield db
        finally:
            db.close()
    return db_generator

# API接口使用:
@router.post("/post")
async def post_request(
    db: Session = Depends(database.get_db(string_here="string"))
):
    return ...

以上三种方案都能让Depends()获取到合法的可调用对象,执行时会正确生成数据库会话,解决TypeError问题。

内容的提问来源于stack exchange,提问作者STY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:10:30