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}