AgentLint 实测验证 100/100实证最佳实践起步模板(基于 929 个 Python 仓库规则)
FastAPI(Python) CLAUDE.md & AGENTS.md 模板
Async/Sync 阻塞隔离、Pydantic v2 响应模型守卫、Alembic 迁移与秒级 pytest 循环。
# FastAPI Service — Python API Harness Python 3.12 FastAPI backend using Pydantic v2, SQLAlchemy 2.0 async, Alembic migrations, and `uv` + `pytest`. ## Commands - Sync deps: `uv sync --dev` - Fast unit test: `uv run pytest tests/unit/test_orders.py -x -q -m "not slow and not network"` - Full suite: `uv run pytest -q` - Lint & typecheck: `uv run ruff check . && uv run ruff format --check . && uv run pyright` - Run dev server: `uv run uvicorn app.main:app --reload` ## Rules - Don't run blocking HTTP (`requests`) or synchronous DB queries inside `async def` routes. Instead use `httpx.AsyncClient` and async SQLAlchemy sessions, or declare the handler as `def`. Because blocking calls stall the entire Uvicorn event loop. - Don't return raw ORM models from endpoints. Instead declare explicit Pydantic v2 `response_model` schemas in `app/schemas/`. Because unguarded ORM serialization leaks internal columns and triggers lazy-load errors. - Don't invoke global `python` or `pip`. Instead prefix every command with `uv run`. Because host Python versions diverge from `uv.lock`. - When editing SQLAlchemy models, read `docs/alembic-migrations.md` before generating revisions. ## Continuity & Safety - Keep `.env`, `.venv/`, and `CLAUDE.local.md` in `.gitignore` — load secrets via `pydantic-settings`. - Record passing `pytest` counts and migration IDs in `HANDOFF.md`.
FastAPI(Python) 开源生态中最常采用的工程规则
参考 4,533 仓库研究中对应主语言生态的高频工程规则采纳率,并结合框架核心防踩坑约束:
pytest测试
pytest test suite (measured in 929 Python corpus repos)
45.9%426 个仓库
type-hints代码规范
Strict type hints & Pydantic schemas (929 Python corpus repos)
29.8%277 个仓库
ruff工具链
Ruff lint and format enforcement (929 Python corpus repos)
29.1%270 个仓库
docker工具链
Containerized API deployment (929 Python corpus repos)
28.6%266 个仓库
uv工具链
uv virtual environment isolation (929 Python corpus repos)
24.5%228 个仓库
必写验证命令(对应规则 W1 与 W7)
- 安装依赖
- uv sync --dev
- 快速单测(秒级迭代)
- uv run pytest tests/unit/test_routes.py -x -q -m 'not slow'
- 全量测试
- uv run pytest -q
- Lint 与静态检查
- uv run ruff check . && uv run ruff format --check . && uv run pyright
- 生产构建
- uv run fastapi check app/main.py
FastAPI(Python) 项目中 AI 代理常见踩坑
- 01在
async def路由中调用同步requests或阻塞 ORM,直接卡死整个 Uvicorn 事件循环。 - 02直接返回 SQLAlchemy ORM 对象而不声明 Pydantic
response_model,泄露内部敏感字段。 - 03修改数据模型后忘记生成并校验 Alembic 迁移脚本。