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 2020-07-16 16:03  麦克煎蛋  阅读(1043)  评论(0编辑  收藏  举报