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}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM