FastAPI 学习之路(二十三)用类作为依赖的注入

发布时间:2022-07-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了FastAPI 学习之路(二十三)用类作为依赖的注入脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

 

我们先看一个简单的demo。

From typing import Optional

from fastapi import DePEnds, FastAPI

app = FastAPI()


fake_ITems_db = [{"city": "beijing"}, {"city": "shanghai"},
                 {"city": "heze"}]


class CommonQueryParams:
    def __init__(self, desc: Optional[str] = None, skip: int = 0, limit: int = 100):
        self.desc = desc
        self.skip = skip
        self.limit = limit
@app.get("/items/")
def read_items(commons: CommonQueryParams = Depends(CommonQueryParams)):
    response = {}
    if commons.desc:
        response.update({"desc": commons.desc})
    items = fake_items_db[commons.skip : commons.skip + commons.limit]
    response.update({"items": items})
    return response

我们去实现了一个类,然后这个类呢,初始化方法方法,我们有介绍,跳过,限制等条件呢,我们在实现接口的时候,去注入下这个类,我们看下结果;

FastAPI 学习之路(二十三)用类作为依赖的注入

 

 

   那么我们看下,我们当增加下,我们注入的类里面需要的参数的时候,看下接口返回的

        

FastAPI 学习之路(二十三)用类作为依赖的注入

 

 

FastAPI 学习之路(二十三)用类作为依赖的注入

 

 

  其实用类实现也没有那么难,有固定的格式。

         我们只需要按照这个格式去实现即可。

        我们有两种写法

 

1.COMmons: CommonQueryParams = Depends(CommonQueryParams)
2.commons: CommonQueryParams = Depends()

 实现的效果都是一样的。

            方法二的写法更加简单,我们去看下接口文档如何展示的。

FastAPI 学习之路(二十三)用类作为依赖的注入

 

 

  正常也会带着这些选填的参数。

我们之前文章有分享过选填必填的参数,我们现在的是否也可以使用呢,我们可以看下,我们必须在依赖注入的时候,必须需要参数desc,我们看下是否可以。

from fastapi import Depends, FastAPI

app = FastAPI()


fake_items_db = [{"city": "beijing"}, {"city": "shanghai"},
                 {"city": "heze"}]


class CommonQueryParams:

    def __init__(self, desc: str , skip: int = 0, limit: int = 100):

        self.desc = desc

        self.skip = skip

        self.limit = limit
@app.get("/items/")
def read_items(commons: CommonQueryParams = Depends()):
    response = {}
    if commons.desc:
        response.update({"desc": commons.desc})
    items = fake_items_db[commons.skip : commons.skip + commons.limit]
    response.update({"items": items})
    return response

        我们看下,我们不填写的时候,是否是给我们返回的异常,我们预期是接口返回异常

    

FastAPI 学习之路(二十三)用类作为依赖的注入

 

 正常填写

FastAPI 学习之路(二十三)用类作为依赖的注入

 

 可以正常返回。那么我们用python的类去实现依赖,其实也是很简单的。之前的一些方法都是可以正常的放在类里面去实现的。

文章首发在公众号,欢迎关注。

FastAPI 学习之路(二十三)用类作为依赖的注入

脚本宝典总结

以上是脚本宝典为你收集整理的FastAPI 学习之路(二十三)用类作为依赖的注入全部内容,希望文章能够帮你解决FastAPI 学习之路(二十三)用类作为依赖的注入所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。