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
原文地址:https://www.cnblogs.com/mazhiyong/p/13066065.html