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}
  • 相关阅读:
    Windows解决端口占用
    Oracle数字格式化
    Windows生成项目目录结构
    IDEA激活教程
    Windows搭建SMB服务
    在右键新建菜单中添加新项目
    Fastjson1.2.47反序列化+环境搭建+漏洞复现
    nmap常用命令及端口
    Shiro反序列化复现
    CVE-2020-0796漏洞复现
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/13323133.html
Copyright © 2011-2022 走看看