工程化全景
现代 Python 工程化已经非常成熟。掌握这套工具链,能让你的项目更专业、更可维护。
工具链全景
项目生命周期
├── 初始化
│ ├── uv / Poetry — 包管理 & 虚拟环境
│ └── cookiecutter — 项目模板
│
├── 开发
│ ├── Ruff — 极速 Linter + Formatter
│ ├── mypy / pyright — 静态类型检查
│ └── pre-commit — Git 提交前检查
│
├── 测试
│ ├── pytest — 测试框架
│ ├── pytest-cov — 覆盖率
│ └── hypothesis — 属性测试
│
├── 配置管理
│ └── pydantic-settings — 环境变量 & 配置文件
│
├── CLI 工具
│ ├── Typer — 基于类型注解的 CLI
│ └── Rich — 终端美化输出
│
└── 部署
├── Docker — 容器化
├── gunicorn — WSGI 服务器
└── uvicorn — ASGI 服务器推荐项目配置
pyproject.toml — 现代项目配置
toml
[project]
name = "my-project"
version = "0.1.0"
description = "项目描述"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.110.0",
"pydantic>=2.0.0",
"sqlalchemy>=2.0.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0.0",
"pytest-cov",
"ruff",
"mypy",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
# Ruff 配置
[tool.ruff]
line-length = 88
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "B", "SIM"]
ignore = ["E501"]
[tool.ruff.format]
quote-style = "double"
# mypy 配置
[tool.mypy]
python_version = "3.11"
strict = true
ignore_missing_imports = true
# pytest 配置
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --cov=src --cov-report=term-missing"快速上手:用 uv 创建项目
bash
# 安装 uv
pip install uv
# 创建新项目
uv init my-project
cd my-project
# 添加依赖
uv add fastapi uvicorn pydantic
# 添加开发依赖
uv add --dev pytest ruff mypy
# 运行
uv run python main.py
uv run pytestpre-commit 配置
yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.9.0
hooks:
- id: mypy
additional_dependencies: [pydantic]bash
pre-commit install # 安装 git hooks
pre-commit run --all-files # 手动运行