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}
  • 相关阅读:
    4、linux-grep awk sed and cuf sort uniq join
    2、linux-compress and uncompresse
    1、linux-wget
    Blast 如何使用Blast+(Linux)转载
    1、R-reshape2-cast
    2、R-reshape2-melt
    doc下批处理文件的感想
    关于大数的四则运算
    hadoop分布式安装教程(转)
    关于java中sizeof的问题
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/13323133.html
Copyright © 2011-2022 走看看