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

发布时间 2023-03-26 22:04:53作者: LeoShi2020
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}