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

相关推荐
爱吃羊的老虎7 小时前
【后端】FastAPI的Pydantic 模型
数据库·后端·python·fastapi
Elastic 中国社区官方博客18 小时前
使用 FastAPI 构建 Elasticsearch API
大数据·数据库·python·elasticsearch·搜索引擎·全文检索·fastapi
陈小桔1 天前
SQLALchemy
python·fastapi
**梯度已爆炸**3 天前
Python Web框架详解:Flask、Streamlit、FastAPI
python·flask·fastapi·streamlit
斟的是酒中桃3 天前
基于Transformer的智能对话系统:FastAPI后端与Streamlit前端实现
前端·transformer·fastapi
蓝倾4 天前
淘宝获取商品分类接口操作指南
前端·后端·fastapi
蓝倾4 天前
1688平台根据关键词获取商品API接口操作指南
前端·后端·fastapi
蓝倾4 天前
京东商品评论API接口实战指南
前端·后端·fastapi
向宇it6 天前
【实现100个unity特效】unity中使用ShaderGraph实现一个贴图UV循环移动滚动的指示效果
游戏·3d·unity·c#·游戏引擎·贴图·uv