zoukankan      html  css  js  c++  java
  • 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}
  • 相关阅读:
    通过串口工具下发指令的Python脚本
    启动app-inspector报Internal Server Error
    IOS版App的控件元素定位
    Webview页面的控件元素定位
    Android版App的控件元素定位
    将Xcode升级到10.0以上版本,Appium启动报错的问题
    IOS版DesiredCapabilities参数配置
    Android版DesiredCapabilities参数配置
    Cannot instantiate the type AppiumDriver,AppiumDriver升级引发的问题
    持续集成-jenkins 环境搭建
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/13323133.html
Copyright © 2011-2022 走看看