随笔 - 214  文章 - 12  评论 - 40  阅读 - 38万

FastAPI 依赖注入系统(六) 可参数化的依赖项

作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

 

我们前面使用的依赖项都是固定的函数或者类,但有时候我们想在依赖项中设置不同的参数,同时又不用声明不同的函数或类。

我们可以利用一个可调用的类实例来实现这个功能。

可调用的实例

注意,类本身就是可调用的,而它的实例需要实现一个特定类方法才是可调用的:__call__

如下所示的类以及它的实例都是可调用的:

class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
if q:
            return self.fixed_content in q
        return False

创建实例

然后我们创建一个类的实例(我们可以指定不同的初始化参数):

checker = FixedContentQueryChecker("bar")

实例作为依赖项

这里我们把类的实例checker而不是类本身FixedContentQueryChecker作为依赖项。

@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}

FastAPI会用如下方式调用依赖项:

checker(q="somequery")

备注,这里的q是传递过来的查询参数。

完整示例

复制代码
from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}
复制代码

 

posted on   麦克煎蛋  阅读(1166)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示