· 约 3 分钟

16-FastAPI进阶-依赖注入

  • FastAPI
  • Python

学习目标

核心概念

代码示例

from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException, Query

app = FastAPI()


def verify_token(x_token: Annotated[str, Header()]):
    if x_token != "fastapi-course":
        raise HTTPException(status_code=401, detail="令牌无效")
    return x_token


def get_pagination(
    page: Annotated[int, Query(ge=1)] = 1,
    size: Annotated[int, Query(ge=1, le=50)] = 10,
):
    return {
        "page": page,
        "size": size,
        "offset": (page - 1) * size,
    }


@app.get("/articles")
def get_articles(
    _: Annotated[str, Depends(verify_token)],
    pagination: Annotated[dict, Depends(get_pagination)],
):
    return {
        "message": "获取文章成功",
        "pagination": pagination,
    }

案例理解

易错点

我的补充