使用UV管理FastAPI项目

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

现有FastAPI项目迁移

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

bash 复制代码
project
└── app
    ├── __init__.py
    ├── main.py
    ├── dependencies.py
    ├── routers
    │   ├── __init__.py
    │   ├── items.py
    │   └── users.py
    └── internal
        ├── __init__.py
        └── admin.py

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

bash 复制代码
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文件内容类似以下内容:

toml 复制代码
[project]
name = "uv-fastapi-example"
version = "0.1.0"
description = "FastAPI project"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "fastapi[standard]",
]

现在,就可以运行FastAPI应用:

bash 复制代码
uv run fastapi dev

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

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

部署

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

bash 复制代码
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:

bash 复制代码
docker build -t fastapi-app .

在本地运行Docker容器:

bash 复制代码
docker run -p 8000:80 fastapi-app

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

相关推荐
曲幽3 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
CaffeinePro7 天前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
jay神9 天前
基于 FastAPI + Vue 的宠物领养管理系统
前端·vue.js·python·毕业设计·fastapi·宠物
染指111010 天前
6.AI大模型-搭建本地大模型服务体系
fastapi·oneapi
CG_MAGIC10 天前
3ds Max材质编辑器:精简模式与Slate模式对比
3d·编辑器·材质·贴图·uv·建模教程
玉夏10 天前
【Shader基础】UV 与纹理采样 Part1
unity·着色器·uv
codeaideaai11 天前
使用UV创建python项目
python·fastapi·uv
milo.qu11 天前
Python工程工具链:uv + 虚拟环境
uv
放下华子我只抽RuiKe511 天前
FastAPI 全栈后端(八):部署与运维
运维·数据库·react.js·oracle·数据挖掘·前端框架·fastapi
SilentSamsara11 天前
模型部署实战:FastAPI + ONNX + Docker 的推理服务化
人工智能·pytorch·python·深度学习·机器学习·fastapi