使用UV管理FastAPI项目

发布于:2025-07-21 ⋅ 阅读:(15) ⋅ 点赞:(0)

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

现有FastAPI项目迁移

例如一个如下结构的FastAPI项目:

project
└── app
    ├── __init__.py
    ├── main.py
    ├── dependencies.py
    ├── routers
    │   ├── __init__.py
    │   ├── items.py
    │   └── users.py
    └── internal
        ├── __init__.py
        └── admin.py

要使用uv,在项目目录下运行:

uv init --app

创建应用框架和pyproject.toml文件。

然后,增加FastAPI依赖:

uv add fastapi --extra standard

项目框架变化为:

project
├── pyproject.toml
└── app
    ├── __init__.py
    ├── main.py
    ├── dependencies.py
    ├── routers
    │   ├── __init__.py
    │   ├── items.py
    │   └── users.py
    └── internal
        ├── __init__.py
        └── admin.py

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应用:

uv run fastapi dev

uv run自动解析和锁定项目依赖库,创建uv.lock,创建虚拟环境,在该环境中运行指令。

在浏览器中打开http://127.0.0.1:8000/?token=jessica进行测试。

部署

可以使用一下Dockerfile在Docker中部署FastAPI应用程序。

FROM python:3.12-slim

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

# Copy the application into the container.
COPY . /app

# Install the application dependencies.
WORKDIR /app
RUN uv sync --frozen --no-cache

# Run the application.
CMD ["/app/.venv/bin/fastapi", "run", "app/main.py", "--port", "80", "--host", "0.0.0.0"]

构建Docker image:

docker build -t fastapi-app .

在本地运行Docker容器:

docker run -p 8000:80 fastapi-app

在浏览器中打开http://127.0.0.1:8000/?token=jessica进行验证和测试。


网站公告

今日签到

点亮在社区的每一天
去签到