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

FastAPI 依赖注入系统(二) 依赖项类

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

 

目前为止,我们看到的依赖项的声明都是函数。实际上这只是声明依赖项的方式之一。

依赖项只要是可调用的即可。Python类也是可调用的。因此在FastAPI中,我们可以用Python类作为依赖项。

 

依赖项类

我们首先把依赖项函数:

async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

转换成依赖项类:

class CommonQueryParams:
    def __init__(self, q: str = None, skip: int = 0, limit: int = 100):
        self.q = q
        self.skip = skip
        self.limit = limit

注意,这里我们用了__init__方法来实现类的初始化。并且类的初始化参数与依赖项函数完全相同。

使用依赖项类

复制代码
from fastapi import Depends, FastAPI

app = FastAPI()


fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


class CommonQueryParams:
    def __init__(self, q: str = None, skip: int = 0, limit: int = 100):
        self.q = q
        self.skip = skip
        self.limit = limit


@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends(CommonQueryParams)):
    response = {}
    if commons.q:
        response.update({"q": commons.q})
    items = fake_items_db[commons.skip : commons.skip + commons.limit]
    response.update({"items": items})
    return response
复制代码

 

posted on   麦克煎蛋  阅读(1276)  评论(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工具
历史上的今天:
2012-06-08 CentOS下配置iptables防火墙
2012-06-08 NSAutoreleasePool自动释放池
2012-06-08 ios中提示信息的实现及自动消失
2012-06-08 文章逐步迁移过来
2012-06-08 什么是Toll-free bridging
2012-06-08 CFArrayRef和NSArray
2012-06-08 ios导航条添加按钮
< 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

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