蓝色天空网mbsky.com · 知识 · 实践 · 创造FastAPI · 本地阅读预览
教程 / Python / 数据科学 / FastAPI

FastAPI 依赖注入

把分页、分层校验和资源管理放入可复用的依赖,并观察请求如何依次执行这些函数。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

依赖的输入和输出

传感器与站点两个接口都需要同一组分页参数。把查询词 q、起始位置 offset 和数量 count 放在 paging 函数中,两个路由共享同一个类型别名 Page。FastAPI 匹配路由后解析依赖的输入,先调用依赖,再把返回值传给路由。

依赖的签名可以像路由一样声明查询参数、路径参数、请求体或请求头。本站实验用字符串 count=4 得到整数 4,省略 offset 时使用 0。发送 count=many 会收到 422,错误位置是 query.count。

旧式参数默认值可写成 page: dict = Depends(paging)。用 Annotated 把 Python 类型与 FastAPI 元数据并列后,别名也能跨路由复用。字典来自 paging 的返回值,依赖对象不会作为业务参数值传入路由。

类和子依赖

依赖可以是可调用的类。window 的注解给出 Window 类型,Depends() 从该类型找到可调用对象,再根据构造函数签名填充 offset 和 count,路由从实例属性读取值。需要把注解类型和实际依赖分开时,可显式传入 Depends(Window)。

classify 依赖 extract。请求日志顺序为 extract、classify、route。省略 q 得到 None,q=standard 保留查询词并得到普通标志,q=urgent 得到优先标志。依赖链中每层都能接收上游结果。

装饰器依赖与应用级依赖

装饰器的 dependencies 列表适合只需执行校验的情况。本站用公开实验值 lab-read 演示:缺 X-Lab-Key 时字段校验返回 422,错值经过 verify 后返回 400,只有正确值才执行路由。成功响应只包含 access,verify 的返回值不会被注入。

在 FastAPI(dependencies=[Depends(verify)]) 中声明的依赖应用于该 FastAPI 实例的路径操作。实验分别请求挂载应用的 /restricted/status 和 /restricted/report,两条路径都必须通过检查。父应用的 /stations 依然无需头部。真实鉴权需要单独设计凭据、安全存储及错误策略。

用 yield 管理请求资源

open_buffer 先打开内存文本流,再 yield 给 report_reader。读取阶段看到的流处于打开状态。退出时先执行 reader 的清理,再由 open_buffer 的 finally 关闭流。这种反向退出顺序让上层在清理时仍能使用下层资源。

本站分别请求 /resource 和 /resource?fail=true。第一条返回日志文本和 HTTP 200,第二条返回 HTTP 409。两次都观察到 open、reader-enter、read、reader-exit、close,最后 closed 为 true。

需要比较默认请求作用域与 scope='function' 的清理时机时,应使用真实流式响应另测。这里的日志比较的是普通响应和受控异常下的释放顺序。依赖中如捕获异常,通常应继续抛出或显式转换为要发送的 HTTP 错误。

函数依赖的三个位置

位置含义
可调用依赖 paging从查询字符串取值和应用默认值,组装成字典。
依赖声明 Depends(paging)交给 FastAPI 解析输入并调用 paging,两个路由可以共用。
路由参数 page: Page路由收到函数返回的字典,可以直接读取三个字段。

从分页到异常清理的依赖实验

python · 阅读源码
from io import StringIO
from typing import Annotated

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


def paging(q: str | None = None, offset: int = 0, count: int = 20):
    return {"q": q, "offset": offset, "count": count}


Page = Annotated[dict, Depends(paging)]
app = FastAPI()


@app.get("/stations")
@app.get("/sensors")
def inventory(page: Page):
    return page


class Window:
    def __init__(self, offset: int = 0, count: int = 20):
        self.offset = offset
        self.count = count


@app.get("/window")
def window(value: Annotated[Window, Depends()]):
    return {"start": value.offset, "size": value.count}


def extract(request: Request, q: str | None = None):
    request.state.order = ["extract"]
    return q


def classify(request: Request, value: Annotated[str | None, Depends(extract)]):
    request.state.order.append("classify")
    return {"q": value, "priority": value == "urgent"}


@app.get("/classify")
def show(request: Request, value: Annotated[dict, Depends(classify)]):
    request.state.order.append("route")
    return {**value, "order": request.state.order}


def verify(request: Request, x_lab_key: Annotated[str, Header()]):
    request.app.state.guard_calls.append("guard")
    if x_lab_key != "lab-read":
        raise HTTPException(status_code=400, detail="invalid lab key")
    return "internal guard value"


app.state.guard_calls = []


@app.get("/private-status", dependencies=[Depends(verify)])
@app.get("/private-report", dependencies=[Depends(verify)])
def guarded(request: Request):
    request.app.state.guard_calls.append("route")
    return {"access": "granted"}


protected = FastAPI(dependencies=[Depends(verify)])
protected.state.guard_calls = []


@protected.get("/status")
@protected.get("/report")
def protected_routes(request: Request):
    request.app.state.guard_calls.append("route")
    return {"access": "granted"}


app.mount("/restricted", protected)


def open_buffer(request: Request):
    buffer = StringIO("station log")
    request.app.state.resource_log.append(("open", buffer.closed))
    try:
        yield buffer
    finally:
        buffer.close()
        request.app.state.resource_log.append(("close", buffer.closed))


def report_reader(
    request: Request, buffer: Annotated[StringIO, Depends(open_buffer)]
):
    request.app.state.resource_log.append(("reader-enter", buffer.closed))
    try:
        yield buffer
    finally:
        request.app.state.resource_log.append(("reader-exit", buffer.closed))


app.state.resource_log = []


@app.get("/resource")
def resource(request: Request, buffer: Annotated[StringIO, Depends(report_reader)],
             fail: bool = False):
    request.app.state.resource_log.append(("read", buffer.closed))
    if fail:
        raise HTTPException(status_code=409, detail="reading interrupted")
    return {"text": buffer.read()}
预期结果 · 待实际运行核验
  • 两个分页接口能复用同一组查询规则。子依赖依次执行,错误请求头阻断路由,内存文本流在成功和异常时都被关闭。
从分页到异常清理的依赖实验

所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

当前源码 SHA256:ba1ea9881dfdbf392ab0717bf78ed756f537d8b26ccc5da5b760bd5afba1d8f4

下载本站示例源码

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本站 FastAPI 实验工程

所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

ZIP SHA256:0228344dce0072112a28ccfb717737e727288de0b3d7168eeda40118a364fc34

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

省略 q 请求 /classify,再传入 urgent。分别记录 q、priority 和 order。

展开参考解答

省略时 q 为 null,priority 为 false。传 urgent 时 q 为 urgent,priority 为 true。两次 order 均为 extract、classify、route。

规范与官方依据