作者:麥克煎蛋 出處: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}