使用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进行验证和测试。

相关推荐
曲幽21 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽3 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽4 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤5 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽5 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再6 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
Li emily6 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi
SCBAiotAigc6 天前
2026.2.25:conda与uv并存时,如何取消base激活
人工智能·python·conda·uv
司徒轩宇6 天前
FastAPI + Uvicorn 深度理解与异步模型解析
fastapi