概览
本文介绍现代 Python 项目的搭建方式,包括:
- 用
pyproject.toml配置项目,取代setup.py和requirements.txt - 区分开发依赖,包括测试和文档依赖
- 用 Ruff 检查与格式化代码,用 Mypy 检查类型
- 用 Docker Compose 运行含 PostgreSQL 的服务
pyproject.toml:现代项目配置标准
pyproject.toml 是现代 Python 项目配置的标准(PEP 518、517、621),可以将原先由 setup.py、setup.cfg 和 requirements.txt 承担的配置集中到一个文件中。
基本结构
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my-api-service"
version = "0.1.0"
description = "FastAPI service with LLM integration"
readme = "README.md"
requires-python = ">=3.11"
license = {text = "MIT"}
authors = [
{name = "Your Name", email = "[email protected]"}
]
# Core dependencies
dependencies = [
"fastapi>=0.104.0",
"hypercorn>=0.15.0",
"tiktoken>=0.5.0",
"json-repair>=0.28.0",
"jinja2>=3.1.0",
"sqlalchemy>=2.0.0",
"openai>=1.0.0",
"psycopg2-binary>=2.9.0",
]
[project.optional-dependencies]
# Development dependencies
dev = [
"pytest>=7.4.0",
"pytest-cov>=4.1.0",
"pytest-asyncio>=0.21.0",
"httpx>=0.25.0", # For testing FastAPI
]
# Documentation dependencies
docs = [
"sphinx>=7.0.0",
"sphinx-rtd-theme>=1.3.0",
]
# Linting and type checking
lint = [
"ruff>=0.1.0",
"mypy>=1.7.0",
]
# All development tools
all = [
"my-api-service[dev,docs,lint]",
]
[project.scripts]
# CLI entry points
my-api = "my_api_service.main:run"
[project.urls]
Homepage = "https://github.com/yourname/my-api-service"
Documentation = "https://my-api-service.readthedocs.io"
Repository = "https://github.com/yourname/my-api-service"
安装可选依赖
# Install core dependencies only (production)
pip install .
# Install with development dependencies
pip install -e ".[dev]"
# Install with all development tools
pip install -e ".[all]"
# Install specific groups
pip install -e ".[dev,lint]"
-e 开启可编辑安装,改动源码即可生效,无需重新安装。
doctest 所需依赖应放在生产环境还是开发环境?
📓 注意: 默认情况下,生产构建不会运行文档字符串内的 doctest。只有显式执行相应测试命令才会运行。
什么时候会运行 doctest?
以下场景会运行:
- 执行
pytest --doctest-modules - 执行
python -m doctest module.py - CI/CD 流水线在测试阶段运行相应命令
哪些场景不会运行?
pip install .(安装生产包)python -m my_module(运行模块)- 生产环境的 Docker 构建
doctest 示例
def calculate_tokens(text: str) -> int:
"""
Calculate the number of tokens in text using tiktoken.
Examples:
>>> calculate_tokens("Hello world")
2
>>> calculate_tokens("")
0
"""
import tiktoken
encoder = tiktoken.get_encoding("cl100k_base")
return len(encoder.encode(text))
如果函数在运行时需要某项依赖(如本例的 tiktoken),即使 doctest 也用到了它,也应该放在核心依赖里。如果仅测试示例使用,函数本身不需要,则放在 dev 依赖中。
用 Ruff 检查和格式化代码
Ruff 是用 Rust 编写的高速 Python 检查器和格式化工具,可承担多种工具的工作:
- Flake8(检查编码风格)
- isort(对 import 排序)
- Black(代码格式化)
- 以及更多工具的工作
在 pyproject.toml 中配置 Ruff
[tool.ruff]
# Target Python version
target-version = "py311"
# Line length
line-length = 88
# Exclude directories
exclude = [
".git",
".venv",
"__pycache__",
"build",
"dist",
]
[tool.ruff.lint]
# Enable rules
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # Pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"ARG", # flake8-unused-arguments
"SIM", # flake8-simplify
]
# Ignore specific rules
ignore = [
"E501", # line too long (handled by formatter)
"B008", # do not perform function calls in argument defaults
]
[tool.ruff.lint.per-file-ignores]
# Ignore unused imports in __init__.py
"__init__.py" = ["F401"]
# Ignore all in tests
"tests/**" = ["ARG", "S101"]
[tool.ruff.format]
# Use double quotes
quote-style = "double"
# Indent with spaces
indent-style = "space"
运行 Ruff
# Check for linting errors
ruff check .
# Fix auto-fixable issues
ruff check --fix .
# Format code
ruff format .
# Check formatting without changing files
ruff format --check .
用 Mypy 做静态类型检查
Mypy 对 Python 代码做静态类型分析,可以在运行前发现类型错误。
在 pyproject.toml 中配置 Mypy
[tool.mypy]
python_version = "3.11"
# Strict mode options
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
# Show error codes
show_error_codes = true
# Exclude directories
exclude = [
"tests/",
"build/",
"dist/",
]
# Per-module configuration
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
[[tool.mypy.overrides]]
module = [
"tiktoken.*",
"json_repair.*",
]
ignore_missing_imports = true
运行 Mypy
# Check entire project
mypy src/
# Check specific file
mypy src/my_module.py
# Generate HTML report
mypy src/ --html-report mypy_report
类型注解示例
from typing import Optional, List, Dict, Any
from collections.abc import Callable
def process_prompt(
template: str,
variables: Dict[str, Any],
max_tokens: Optional[int] = None,
) -> str:
"""Process a Jinja template with variables."""
from jinja2 import Template
rendered = Template(template).render(**variables)
return rendered
async def fetch_completion(
messages: List[Dict[str, str]],
callback: Optional[Callable[[str], None]] = None,
) -> str:
"""Fetch completion from OpenAI."""
...
配置 pytest
[tool.pytest.ini_options]
minversion = "7.0"
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_functions = ["test_*"]
# Asyncio mode
asyncio_mode = "auto"
# Add options
addopts = [
"-v",
"--tb=short",
"--strict-markers",
"-ra",
]
# Markers
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration tests",
]
# Coverage options
[tool.coverage.run]
source = ["src"]
branch = true
omit = ["tests/*", "*/__init__.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"raise NotImplementedError",
"if TYPE_CHECKING:",
]
配置 Docker Compose
compose.yml:生产服务
services:
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/myapp
- OPENAI_API_KEY=${OPENAI_API_KEY}
depends_on:
db:
condition: service_healthy
restart: unless-stopped
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- POSTGRES_DB=myapp
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:
compose.test-deps.yml:测试依赖
这个文件提供集成测试需要的外部服务,应用本身另行启动。
# compose.test-deps.yml
# Usage: docker compose -f compose.test-deps.yml up -d
services:
test-db:
image: postgres:16-alpine
ports:
- "5433:5432" # Different port to avoid conflict with dev DB
environment:
- POSTGRES_USER=testuser
- POSTGRES_PASSWORD=testpass
- POSTGRES_DB=testdb
tmpfs:
- /var/lib/postgresql/data # Use tmpfs for faster tests
healthcheck:
test: ["CMD-SHELL", "pg_isready -U testuser -d testdb"]
interval: 2s
timeout: 2s
retries: 10
test-redis:
image: redis:7-alpine
ports:
- "6380:6379" # Different port to avoid conflict
command: redis-server --appendonly no # Faster for tests
如何使用 compose.test-deps.yml
# Start test dependencies before running tests
docker compose -f compose.test-deps.yml up -d
# Wait for services to be healthy
docker compose -f compose.test-deps.yml ps
# Run tests (pointing to test services)
DATABASE_URL=postgresql://testuser:testpass@localhost:5433/testdb pytest
# Run specific integration tests
DATABASE_URL=postgresql://testuser:testpass@localhost:5433/testdb \
pytest tests/integration/ -m integration
# Stop test dependencies
docker compose -f compose.test-deps.yml down
# Stop and remove volumes (clean slate)
docker compose -f compose.test-deps.yml down -v
集成 CI/CD
在 GitHub Actions 或其他 CI 系统中可以这样写:
# .github/workflows/test.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpass
POSTGRES_DB: testdb
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -e ".[dev,lint]"
- name: Lint with Ruff
run: |
ruff check .
ruff format --check .
- name: Type check with Mypy
run: mypy src/
- name: Run tests
env:
DATABASE_URL: postgresql://testuser:testpass@localhost:5432/testdb
run: pytest --cov=src --cov-report=xml
生产环境的 Dockerfile
# Dockerfile
FROM python:3.11-slim as builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Copy only dependency files first (layer caching)
COPY pyproject.toml .
COPY src/ src/
# Install production dependencies only
RUN pip install --no-cache-dir .
# Production stage
FROM python:3.11-slim
WORKDIR /app
# Copy installed packages from builder
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
# Copy application code
COPY src/ src/
# Create non-root user
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["hypercorn", "src.main:app", "--bind", "0.0.0.0:8000"]
完整的 pyproject.toml 示例
下面是一个 FastAPI + LLM 服务的完整示例:
# =============================================================================
# BUILD SYSTEM - Defines how to build the package
# =============================================================================
[build-system]
# Packages required to build this project (not runtime dependencies)
requires = ["setuptools>=61.0", "wheel"]
# The build backend to use (setuptools is the most common)
build-backend = "setuptools.build_meta"
# =============================================================================
# PROJECT METADATA - Core project information (PEP 621)
# =============================================================================
[project]
# Package name on PyPI (use hyphens, not underscores)
name = "my-llm-api"
# Semantic versioning: MAJOR.MINOR.PATCH
version = "0.1.0"
# One-line description shown on PyPI
description = "FastAPI service with LLM integration"
# Path to README file (supports .md, .rst, .txt)
readme = "README.md"
# Minimum Python version required
requires-python = ">=3.11"
# License identifier
license = {text = "MIT"}
# Runtime dependencies - installed with `pip install .`
# These are REQUIRED for the package to function
dependencies = [
# Web framework - FastAPI for async API, Hypercorn as ASGI server
"fastapi>=0.104.0", # Async web framework
"hypercorn>=0.15.0", # ASGI server (alternative to uvicorn)
# LLM tools
"tiktoken>=0.5.0", # OpenAI tokenizer for counting tokens
"openai>=1.0.0", # Official OpenAI Python client
# Data processing
"json-repair>=0.28.0", # Fix malformed JSON from LLM outputs
"jinja2>=3.1.0", # Template engine for prompt building
# Database
"sqlalchemy>=2.0.0", # ORM and database toolkit
"psycopg2-binary>=2.9.0", # PostgreSQL adapter (binary for easy install)
]
# =============================================================================
# OPTIONAL DEPENDENCIES - Installed with `pip install .[group]`
# =============================================================================
[project.optional-dependencies]
# Development/testing dependencies: pip install -e ".[dev]"
dev = [
"pytest>=7.4.0", # Testing framework
"pytest-cov>=4.1.0", # Coverage plugin for pytest
"pytest-asyncio>=0.21.0", # Async test support
"httpx>=0.25.0", # Async HTTP client for testing FastAPI
]
# Documentation dependencies: pip install -e ".[docs]"
docs = [
"sphinx>=7.0.0", # Documentation generator
"sphinx-rtd-theme>=1.3.0", # Read the Docs theme
]
# Linting and type checking: pip install -e ".[lint]"
lint = [
"ruff>=0.1.0", # Fast linter and formatter (replaces flake8, black, isort)
"mypy>=1.7.0", # Static type checker
]
# All development tools: pip install -e ".[all]"
# References other groups using self-referential syntax
all = [
"my-llm-api[dev,docs,lint]",
]
# =============================================================================
# SETUPTOOLS CONFIGURATION - Package discovery
# =============================================================================
[tool.setuptools.packages.find]
# Look for packages in the "src" directory (src layout)
# This means your code lives in src/my_llm_api/
where = ["src"]
# =============================================================================
# RUFF - Fast Python linter and formatter (replaces flake8, black, isort)
# =============================================================================
[tool.ruff]
# Target Python version for syntax checks
target-version = "py311"
# Maximum line length (88 is black's default)
line-length = 88
# Directories to exclude from linting
exclude = [".git", ".venv", "__pycache__", "build", "dist"]
[tool.ruff.lint]
# Rule codes to enable:
# E = pycodestyle errors (indentation, whitespace, etc.)
# W = pycodestyle warnings
# F = Pyflakes (undefined names, unused imports, etc.)
# I = isort (import sorting)
# B = flake8-bugbear (common bugs and design problems)
# C4 = flake8-comprehensions (unnecessary list/dict/set calls)
# UP = pyupgrade (upgrade syntax for newer Python)
# ARG = flake8-unused-arguments
# SIM = flake8-simplify (simplifiable code)
select = ["E", "W", "F", "I", "B", "C4", "UP", "ARG", "SIM"]
# Rules to ignore:
# E501 = line too long (formatter handles this)
# B008 = function calls in default arguments (common in FastAPI: Depends())
ignore = ["E501", "B008"]
[tool.ruff.lint.per-file-ignores]
# F401 = unused import (ok in __init__.py for re-exports)
"__init__.py" = ["F401"]
# ARG = unused arguments (ok in tests for fixtures)
# S101 = use of assert (ok in tests)
"tests/**" = ["ARG", "S101"]
[tool.ruff.format]
# String quote style: "double" or "single"
quote-style = "double"
# Indentation: "space" or "tab"
indent-style = "space"
# =============================================================================
# MYPY - Static type checker
# =============================================================================
[tool.mypy]
# Python version for type checking
python_version = "3.11"
# Enable all strict mode checks (recommended for new projects)
# Includes: disallow_untyped_defs, disallow_incomplete_defs, etc.
strict = true
# Show error codes in output (e.g., [arg-type], [return-value])
show_error_codes = true
# Directories to exclude from type checking
exclude = ["tests/", "build/", "dist/"]
# Per-module overrides for third-party packages without type stubs
[[tool.mypy.overrides]]
# These packages don't have type annotations or stubs
module = ["tiktoken.*", "json_repair.*"]
# Don't error on missing type info for these modules
ignore_missing_imports = true
# =============================================================================
# PYTEST - Testing framework configuration
# =============================================================================
[tool.pytest.ini_options]
# Minimum pytest version required
minversion = "7.0"
# Directories to search for tests
testpaths = ["tests"]
# pytest-asyncio mode: "auto" automatically handles async tests
asyncio_mode = "auto"
# Default command-line options:
# -v = verbose output
# --tb=short = shorter tracebacks
# -ra = show summary of all non-passed tests
addopts = ["-v", "--tb=short", "-ra"]
# =============================================================================
# COVERAGE - Code coverage configuration
# =============================================================================
[tool.coverage.run]
# Directories to measure coverage for
source = ["src"]
# Enable branch coverage (if/else paths)
branch = true
项目结构速查
有两种测试组织方式:只用 doctest 更简单,doctest 搭配独立测试目录能覆盖更复杂的场景。
方案一:只用 doctest
适合库、实用工具以及文档字符串里的示例就足够的小项目。
my-project/
│
├── src/ # Source code directory (src layout)
│ └── my_package/
│ ├── __init__.py
│ ├── main.py # Tests live inside docstrings
│ └── utils.py # Each function has doctest examples
│
├── pyproject.toml # Configure pytest to run doctests
├── Dockerfile
├── .gitignore
└── README.md
含 doctest 的示例:
# src/my_package/utils.py
def calculate_tokens(text: str) -> int:
"""
Calculate the number of tokens in text.
Examples:
>>> calculate_tokens("Hello world")
2
>>> calculate_tokens("")
0
>>> calculate_tokens("This is a longer sentence with more tokens")
8
"""
import tiktoken
encoder = tiktoken.get_encoding("cl100k_base")
return len(encoder.encode(text))
只用 doctest 的 pyproject.toml:
[tool.pytest.ini_options]
minversion = "7.0"
# Run doctests from all modules in src/
addopts = ["--doctest-modules", "-v"]
# Tell pytest where to find modules
pythonpath = ["src"]
运行测试:
pytest # Runs all doctests in src/
pytest --doctest-modules src/ # Explicit path
方案二:doctest 搭配测试目录
适合应用、API,以及需要 fixture、模拟对象或集成测试的项目。
my-project/
│
├── src/ # Source code directory (src layout)
│ │ # Prevents accidental imports from project root
│ │ # Forces you to install package to test it
│ │
│ └── my_package/ # Your actual Python package (use underscores)
│ │ # This name is used for imports: `import my_package`
│ │
│ ├── __init__.py # Makes this directory a Python package
│ │ # Can be empty or contain package-level exports
│ │ # Example: `from .main import app`
│ │
│ ├── main.py # Application entry point + simple doctests
│ │ # Contains FastAPI app, CLI logic, etc.
│ │
│ └── utils.py # Utility/helper functions + doctests
│ # Add more modules as needed (models.py, api.py, etc.)
│
├── tests/ # Test directory for complex tests
│ │ # Mirrors src/ structure for larger projects
│ │
│ ├── __init__.py # Makes tests a package (needed for some pytest configs)
│ │
│ ├── conftest.py # Pytest fixtures shared across all tests
│ │ # Database connections, test clients, mock data, etc.
│ │
│ └── test_main.py # Tests for main.py (prefix with test_)
│ # Add test_utils.py, test_api.py, etc.
│
├── pyproject.toml # Project configuration (replaces setup.py + requirements.txt)
│ # Dependencies, build config, tool settings (ruff, mypy, pytest)
│
├── compose.yml # Docker Compose for production/development services
│ # Defines app container + database + other services
│
├── compose.test-deps.yml # Docker Compose for test dependencies ONLY
│ # Spins up isolated test database, redis, etc.
│ # Uses different ports to avoid conflicts
│
├── Dockerfile # Container build instructions
│ # Multi-stage build: builder stage + slim production stage
│
├── .gitignore # Files/directories to exclude from git
│ # .venv/, __pycache__/, .env, dist/, *.egg-info/
│
└── README.md # Project documentation
# Installation, usage, API docs, contributing guide
何时使用 doctest,何时使用测试目录?
| 对比项 | doctest | tests/ 目录 |
|---|---|---|
| 位置 | 文档字符串中 | 独立测试文件中 |
| 目的 | 简单示例和文档 | 复杂用例和边界情况 |
| 范围 | 单个函数的演示 | 集成测试、fixture 和模拟对象 |
| 最适合回答 | “这个函数怎么用?” | “各种情况下都能正确工作吗?” |
| Fixture | 不支持 | 完整支持 pytest fixture |
| 模拟对象 | 有限 | 完整支持 mock 和 patch |
| 异步 | 不方便 | 原生支持 pytest-asyncio |
以下情况可以使用 doctest:
- 输入和输出都简单的纯函数
- 需要保持准确的文档示例
- 快速检查基本功能
以下情况宜使用 tests/ 目录:
- 数据库或 API 的集成测试
- 需要 fixture 的测试,例如测试客户端或模拟数据
- 包含大量用例的参数化测试
- 异步端点测试
- 错误处理和边界条件
用 tests/ 处理复杂场景的示例
# tests/conftest.py
import pytest
from httpx import AsyncClient
from my_package.main import app
@pytest.fixture
async def client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
@pytest.fixture
def mock_openai(mocker):
return mocker.patch("my_package.llm.openai.ChatCompletion.create")
# tests/test_api.py
import pytest
@pytest.mark.asyncio
async def test_generate_endpoint(client, mock_openai):
mock_openai.return_value = {"choices": [{"message": {"content": "Hello"}}]}
response = await client.post("/generate", json={"prompt": "Hi"})
assert response.status_code == 200
assert response.json()["result"] == "Hello"
@pytest.mark.parametrize("invalid_input", [None, "", {"wrong": "format"}])
async def test_generate_validation(client, invalid_input):
response = await client.post("/generate", json=invalid_input)
assert response.status_code == 422
为什么使用 src/ 布局?
相比平铺布局,推荐 src/ 布局的原因如下:
- 避免意外导入。 未安装时,在项目根目录运行
import my_package不会误导入本地源码。 - 要求正确安装。 更容易确认包在开发和生产环境中的行为一致。
- 保持根目录清晰。 把代码和配置文件分开。
- 避免修改导入路径。 无需为
sys.path写变通代码。
# Flat layout (NOT recommended)
my-project/
├── my_package/ # Can be imported without installing!
├── tests/
└── pyproject.toml
# Src layout (recommended)
my-project/
├── src/
│ └── my_package/ # Must install to import
├── tests/
└── pyproject.toml
常用命令速查
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Unix
.venv\Scripts\activate # Windows
# Install with all dev dependencies
pip install -e ".[all]"
# Run quality checks
ruff check . # Linting
ruff format --check . # Format check
mypy src/ # Type checking
# Run tests
pytest # All tests
pytest --cov=src # With coverage
pytest -m "not slow" # Skip slow tests
# Docker
docker compose up -d # Start services
docker compose -f compose.test-deps.yml up -d # Start test deps
docker compose down -v # Stop and clean
# Build and publish
pip install build twine
python -m build
twine upload dist/*
总结
| 工具 | 用途 |
|---|---|
| pyproject.toml | 集中管理项目配置 |
| Ruff | 快速检查并格式化代码,可取代 flake8、black 和 isort |
| Mypy | 静态类型检查 |
| pytest | 测试框架 |
| Docker Compose | 编排服务 |
| compose.test-deps.yml | 提供测试用的外部依赖 |
💡 提示: 提交前运行
ruff check --fix . && ruff format . && mypy src/,可以尽早发现问题。