基于 Poetry 2.x 的 FastAPI 开发环境搭建

58 阅读2分钟

基于 Poetry 2.x 的 FastAPI 开发环境搭建

说明:本文以 Poetry 2.2.1 为例,其他版本命令与输出可能略有差异。

目录

目的

基于 Poetry 搭建 FastAPI 开发环境,为后续项目开发奠定基础。

关键词

  • poetry
  • fastapi
  • uvicorn

搭建步骤

安装 Poetry

Poetry 是 Python 项目与依赖的现代化管理工具,详见官方文档

# 安装 Poetry(推荐使用 Homebrew)
brew install poetry

# 查看 Poetry 版本(本文以 2.2.1 为例)
poetry --version

创建新项目

Poetry 既支持新建项目,也支持在已有目录初始化。这里演示完整新建:

# 创建演示项目(项目目录:fastapi_demo)
poetry new fastapi_demo

创建后目录结构如下:

fastapi_demo
├── README.md
├── pyproject.toml
├── src
│   └── fastapi_demo
│       └── __init__.py
└── tests
    └── __init__.py

其中 pyproject.toml 用于协调你的项目与其依赖,示例内容如下(关键段落已高亮):

[project]
name = "fastapi_demo"
version = "0.1.0"
description = ""
authors = [
    { name = "witsnail", email = "witsnail@gmail.com" }
]
readme = "README.md"
requires-python = ">=3.14"
dependencies = []

[tool.poetry]
packages = [{ include = "fastapi_demo", from = "src" }]

[build-system]
requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"

需要特别注意的是:

[tool.poetry]
packages = [{ include = "fastapi_demo", from = "src" }]

这表示 Python 包(可导入的源码模块)位于 src 目录下,包名为 fastapi_demo。此配置直接影响项目的打包分发、模块导入与依赖安装等关键场景。

安装 FastAPI 依赖

FastAPI 开发需要 fastapiuvicorn 两个依赖:

# 添加依赖
poetry add fastapi uvicorn

安装完成后,Poetry 会在 pyproject.toml 中写入对应依赖约束,例如:

dependencies = [
    "fastapi (>=0.123.0,<0.124.0)",
    "uvicorn (>=0.38.0,<0.39.0)"
]

编写示例应用

src/fastapi_demo 下新建 main.py

# 新建 main.py 文件
touch src/fastapi_demo/main.py

main.py 内容如下:

from fastapi import FastAPI

app = FastAPI(
    title="My FastAPI Application",
    description="This is a sample FastAPI application with custom metadata.",
    version="1.0.0",
)

@app.get("/", tags=["Root"])
async def root():
    """Root endpoint returning a welcome message."""
    return {"message": "Hello from Poetry + FastAPI!"}

运行并验证

在项目根目录 fastapi_demo 下执行:

poetry run uvicorn fastapi_demo.main:app --reload --host 0.0.0.0 --port 8000

看到如下输出即表示启动成功:

INFO:     Will watch for changes in these directories: ['.../fastapi_demo']
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [7062] using StatReload
INFO:     Started server process [7070]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

然后访问 http://127.0.0.1:8000/ 即可看到返回的问候语。

添加便捷启动命令

为避免每次输入冗长命令,我们可以添加一个脚本入口。在 src/fastapi_demo 下添加 cli.py

touch src/fastapi_demo/cli.py

内容如下:

"""命令行入口脚本"""
import uvicorn

def serve():
    """启动 FastAPI 开发服务器"""
    uvicorn.run(
        "fastapi_demo.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
    )

pyproject.toml 中添加脚本映射:

[tool.poetry.scripts]
serve = "fastapi_demo.cli:serve"

现在即可通过以下命令一键启动:

poetry run serve

结论

至此,已完成基于 Poetry 的 FastAPI 开发环境搭建与便捷启动配置。