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

如何在FastAPI中使用add_route()为端点传递参数?

问题原因

你直接调用my_function(clientname='my_other_client')时,异步函数会立即返回一个协程对象,而FastAPI的add_route需要接收一个可调用的异步函数(用于请求到来时执行),不是已经执行的协程,因此触发TypeError: 'coroutine' object is not callable错误。

解决方案

以下是两种可行的实现方式:

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

通过partial可以固定函数的部分参数,生成一个新的可调用函数,不会立即执行原函数:

from functools import partial
from fastapi import Request

async def my_function(request: Request, clientname='my_client'):
    print(request.method)
    print(clientname)
    # 其他逻辑
    return {"status": "ok"}

# 绑定clientname参数,生成新函数
bound_func = partial(my_function, clientname='my_other_client')
private_router.add_route('/api/my/test/route', bound_func, ['GET'])

方法2:编写包装函数

手动创建一个新的异步函数,在内部调用原函数并传入指定参数:

from fastapi import Request

async def my_function(request: Request, clientname='my_client'):
    print(request.method)
    print(clientname)
    # 其他逻辑
    return {"status": "ok"}

async def wrapped_func(request: Request):
    return await my_function(request, clientname='my_other_client')

private_router.add_route('/api/my/test/route', wrapped_func, ['GET'])

如果习惯用装饰器风格的路由定义,也可以直接写:

@private_router.get('/api/my/test/route')
async def wrapped_func(request: Request):
    return await my_function(request, clientname='my_other_client')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:30:13