[FastAPI-34]基于类的依赖注入-推荐使用

from fastapi import Depends, FastAPI

app = FastAPI()
'''
基于类的依赖注入
'''

BOOKS = [{"id": i, "name": f"book{i}", "status": i % 4 != 0} for i in range(1, 11)]


# 定义依赖条件
class CommonQueryParams:
    def __init__(self, page: int, size: int, status: bool):
        self.page = page
        self.size = size
        self.status = status


@app.get("/api/books")
# def get_books(commons: CommonQueryParams = Depends(CommonQueryParams)):	    # 使用依赖条件
def get_books(commons: CommonQueryParams = Depends()): # 简写
    page = commons.page
    size = commons.size
    books = [b for b in BOOKS if b["status"] == commons.status]
    return books[(page - 1) * size:page * size]
posted @ 2023-03-26 21:41  LeoShi2020  阅读(32)  评论(0编辑  收藏  举报