2.7.8 与 FastAPI 配合使用

原文链接: https://docs.astral.sh/uv/guides/integration/fastapi/

2.7.8 与 FastAPI 配合使用

FastAPI 是一个现代、高性能的 Python Web 框架。你可以用 uv 管理 FastAPI 项目,包括安装依赖、管理环境、运行 FastAPI 应用等。

注意

本指南的源代码可以在 uv-fastapi-example 仓库中查看。

迁移已有的 FastAPI 项目

以 FastAPI 文档中定义的示例应用为例,其结构如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
project
└── app
    ├── __init__.py
    ├── main.py
    ├── dependencies.py
    ├── routers
    │   ├── __init__.py
    │   ├── items.py
    │   └── users.py
    └── internal
        ├── __init__.py
        └── admin.py

要对该应用使用 uv,请在 project 目录中运行:

1
$ uv init --no-package

这会为一个扁平的、不打包的项目创建 pyproject.toml 文件。

然后添加对 FastAPI 的依赖:

1
$ uv add fastapi --extra standard

现在你应该得到如下结构:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
project
├── pyproject.toml
└── app
    ├── __init__.py
    ├── main.py
    ├── dependencies.py
    ├── routers
    │   ├── __init__.py
    │   ├── items.py
    │   └── users.py
    └── internal
        ├── __init__.py
        └── admin.py

而 pyproject.toml 文件的内容大致如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# pyproject.toml
[project]
name = "uv-fastapi-example"
version = "0.1.0"
description = "FastAPI project"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "fastapi[standard]",
]

接着,你可以这样运行 FastAPI 应用:

1
$ uv run fastapi dev

uv run 会自动解析并锁定项目依赖(即在 pyproject.toml 旁边创建 uv.lock)、创建虚拟环境,并在该环境中运行命令。

在浏览器中打开 http://127.0.0.1:8000/?token=jessica 来测试该应用。

部署

要用 Docker 部署 FastAPI 应用,可以使用下面的 Dockerfile:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Dockerfile
FROM python:3.12-slim

# 安装 uv。
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# 把应用复制到容器中。
COPY . /app

# 安装应用依赖。
WORKDIR /app
RUN uv sync --frozen --no-cache

# 运行应用。
CMD ["/app/.venv/bin/fastapi", "run", "app/main.py", "--port", "80", "--host", "0.0.0.0"]

这样构建 Docker 镜像:

1
$ docker build -t fastapi-app .

在本地运行 Docker 容器:

1
$ docker run -p 8000:80 fastapi-app

在浏览器中访问 http://127.0.0.1:8000/?token=jessica 以确认应用运行正常。

提示

关于在 Docker 中使用 uv 的更多内容,请参阅 Docker 指南。

最后修改 September 25, 2026: 更新 (221c74c33)