[FastAPI-35]基于对象的依赖注入

from fastapi import Depends, FastAPI

app = FastAPI(title="基于对象的依赖注入",
              description="检查指定的文本是否在查询参数q中")


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):     # 实例化对象是执行
        self.fixed_content = fixed_content

    def __call__(self, q: str = "") -> bool:    # 对象被调用时执行
        return self.fixed_content in q


@app.get("/hello")
def hello_check(exists: bool = Depends(FixedContentQueryChecker("hello"))):
    return {"exists": exists}


@app.get("/world")
def world_check(exists: bool = Depends(FixedContentQueryChecker("world"))):
    return {"exists": exists}
posted @ 2023-03-26 21:59  LeoShi2020  阅读(34)  评论(0编辑  收藏  举报