FastAPI之基于函数,类作为依赖

from fastapi import APIRouter, Depends
from typing import Optional, List
from pydantic import Field, BaseModel

app05 = APIRouter()


class UserInfo(BaseModel):
    name: str = Field(..., max_length=5, min_length=3, regex=r'^zdd', description='用户名'),
    password: str = Field(default='zhao.555', max_length=12, min_length=6),
    family: List[str] = None


""" 首先,先定义一个公共的函数,依赖注入不区分同步还是异步 """


# 公共函数 ,公共函数作为依赖
def dependences(city: Optional[str] = None, confirm: int = 1, death: int = None):
    return{'city': city, 'confirm': confirm, 'death': death}


@app05.get('/dependence01',
           summary='依赖注入第一个实例,基于子函数dependences',
           description='依赖注入',
           tags=['依赖注入实例1']
           )
async def dependence01(commmen: dict = Depends(dependences)):
    return commmen


fake_items_db = [{'name': 'foo'}, {'name': 'boo'}, {'name': 'coo'}]


# 公共类作为依赖
class BaseDependence:

    def __init__(self, q, page=1, page_num=10):
        self.q = q
        self.page = page
        self.page_num = page_num


@app05.get('/base_class_dependence')
def base_class_dependence(comment=Depends(BaseDependence)):
    response = {}
    if comment.q:
        response.update({'q': comment.q})
    dic_ret = fake_items_db[comment.q: comment.page_num+1]
    response.update({'items': dic_ret})
    return response

 

posted @ 2021-05-29 15:07  苦行僧冬*婷  阅读(214)  评论(0)    收藏  举报