关于 python-patterns
面向 Python 开发者的决策型开发指南,涵盖框架选择、异步与同步、类型提示、项目结构、测试和错误处理。它强调结合项目需求权衡方案,而非照搬固定代码模式。
主要功能
- 01按项目需求选择框架
- 02判断异步或同步方案
- 03类型提示与 Pydantic 校验
- 04规划项目结构与依赖注入
- 05测试及错误处理原则
适用场景
- 01为 API 或全栈项目选择框架
- 02评估 I/O 密集任务的异步方案
- 03规划 Python 服务的模块结构
- 04制定关键路径测试与异常策略
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ vudovn/ ag-kit --skill python-patterns安装后在 Claude Code 中输入/python-patterns确认已加载。
详细介绍
Python 模式
Python 开发原则与决策。 学会思考,而不是死记模式。
⚠️ 如何使用此技能
此技能讲解的是决策原则,而不是可直接复制的固定代码。
- 不确定时,询问用户对框架的偏好
- 根据具体情境选择异步或同步
- 不要每次都默认使用同一个框架
1. 框架选择
决策树
What are you building?
│
├── API-first / Microservices
│ └── FastAPI (async, modern, fast)
│
├── Full-stack web / CMS / Admin
│ └── Django (batteries-included)
│
├── Simple / Script / Learning
│ └── Flask (minimal, flexible)
│
├── AI/ML API serving
│ └── FastAPI (Pydantic, async, uvicorn)
│
└── Background workers
└── Celery + any framework
对比原则
| 因素 | FastAPI | Django | Flask |
|---|---|---|---|
| 最适合 | API、微服务 | 全栈、CMS | 简单项目、学习 |
| 异步 | 原生支持 | Django 5.0+ | 通过扩展支持 |
| 管理后台 | 手动实现 | 内置 | 通过扩展支持 |
| ORM | 自行选择 | Django ORM | 自行选择 |
| 学习曲线 | 低 | 中 | 低 |
需要询问的问题:
- 这是仅提供 API 的项目还是全栈项目?
- 是否需要管理界面?
- 团队是否熟悉异步?
- 是否有现成的基础设施?
2. 异步与同步的选择
何时使用异步
async def is better when:
├── I/O-bound operations (database, HTTP, file)
├── Many concurrent connections
├── Real-time features
├── Microservices communication
└── FastAPI/Starlette/Django ASGI
def (sync) is better when:
├── CPU-bound operations
├── Simple scripts
├── Legacy codebase
├── Team unfamiliar with async
└── Blocking libraries (no async version)
黄金法则
I/O-bound → async (waiting for external)
CPU-bound → sync + multiprocessing (computing)
Don't:
├── Mix sync and async carelessly
├── Use sync libraries in async code
└── Force async for CPU work
异步库的选择
| 需求 | 异步库 |
|---|---|
| HTTP 客户端 | httpx |
| PostgreSQL | asyncpg |
| Redis | redis-py (redis.asyncio) |
| 文件 I/O | aiofiles |
| 数据库 ORM | SQLAlchemy 2.0 async、Tortoise |
3. 类型提示策略
何时添加类型
Always type:
├── Function parameters
├── Return types
├── Class attributes
├── Public APIs
Can skip:
├── Local variables (let inference work)
├── One-off scripts
├── Tests (usually)
常见类型模式
# These are patterns, understand them:
# Optional → might be None
from typing import Optional
def find_user(id: int) -> Optional[User]: ...
# Union → one of multiple types
def process(data: str | dict) -> None: ...
# Generic collections
def get_items() -> list[Item]: ...
def get_mapping() -> dict[str, int]: ...
# Callable
from typing import Callable
def apply(fn: Callable[[int], str]) -> str: ...
使用 Pydantic 进行验证
When to use Pydantic:
├── API request/response models
├── Configuration/settings
├── Data validation
├── Serialization
Benefits:
├── Runtime validation
├── Auto-generated JSON schema
├── Works with FastAPI natively
└── Clear error messages
4. 项目结构原则
结构选择
Small project / Script:
├── main.py
├── utils.py
└── requirements.txt
Medium API:
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── models/
│ ├── routes/
│ ├── services/
│ └── schemas/
├── tests/
└── pyproject.toml
Large application:
├── src/
│ └── myapp/
│ ├── core/
│ ├── api/
│ ├── services/
│ ├── models/
│ └── ...
├── tests/
└── pyproject.toml
FastAPI 结构原则
Organize by feature or layer:
By layer:
├── routes/ (API endpoints)
├── services/ (business logic)
├── models/ (database models)
├── schemas/ (Pydantic models)
└── dependencies/ (shared deps)
By feature:
├── users/
│ ├── routes.py
│ ├── service.py
│ └── schemas.py
└── products/
└── ...
5. Django 原则
Django 异步(Django 5.0+)
Django supports async:
├── Async views
├── Async middleware
├── Async ORM (limited)
└── ASGI deployment
When to use async in Django:
├── External API calls
├── WebSocket (Channels)
├── High-concurrency views
└── Background task triggering
Django 最佳实践
Model design:
├── Fat models, thin views
├── Use managers for common queries
├── Abstract base classes for shared fields
Views:
├── Class-based for complex CRUD
├── Function-based for simple endpoints
├── Use viewsets with DRF
Queries:
├── select_related() for FKs
├── prefetch_related() for M2M
├── Avoid N+1 queries
└── Use .only() for specific fields
6. FastAPI 原则
FastAPI 中的 async def 与 def
Use async def when:
├── Using async database drivers
├── Making async HTTP calls
├── I/O-bound operations
└── Want to handle concurrency
Use def when:
├── Blocking operations
├── Sync database drivers
├── CPU-bound work
└── FastAPI runs in threadpool automatically
依赖注入
Use dependencies for:
├── Database sessions
├── Current user / Auth
├── Configuration
├── Shared resources
Benefits:
├── Testability (mock dependencies)
├── Clean separation
├── Automatic cleanup (yield)
Pydantic v2 集成
# FastAPI + Pydantic are tightly integrated:
# Request validation
@app.post("/users")
async def create(user: UserCreate) -> UserResponse:
# user is already validated
...
# Response serialization
# Return type becomes response schema
7. 后台任务
选择指南
| 方案 | 最适合 |
|---|---|
| BackgroundTasks | 简单的进程内任务 |
| Celery | 分布式、复杂的工作流 |
| ARQ | 异步、基于 Redis |
| RQ | 简单的 Redis 队列 |
| Dramatiq | 基于 Actor,比 Celery 更简单 |
何时使用各方案
FastAPI BackgroundTasks:
├── Quick operations
├── No persistence needed
├── Fire-and-forget
└── Same process
Celery/ARQ:
├── Long-running tasks
├── Need retry logic
├── Distributed workers
├── Persistent queue
└── Complex workflows
8. 错误处理原则
异常策略
In FastAPI:
├── Create custom exception classes
├── Register exception handlers
├── Return consistent error format
└── Log without exposing internals
Pattern:
├── Raise domain exceptions in services
├── Catch and transform in handlers
└── Client gets clean error response
错误响应原则
Include:
├── Error code (programmatic)
├── Message (human readable)
├── Details (field-level when applicable)
└── NOT stack traces (security)
9. 测试原则
测试策略
| 类型 | 目的 | 工具 |
|---|---|---|
| 单元测试 | 业务逻辑 | pytest |
| 集成测试 | API 端点 | pytest + httpx/TestClient |
| 端到端测试 | 完整工作流 | pytest + DB |
异步测试
# Use pytest-asyncio for async tests
import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_endpoint():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/users")
assert response.status_code == 200
Fixture 策略
Common fixtures:
├── db_session → Database connection
├── client → Test client
├── authenticated_user → User with token
└── sample_data → Test data setup
10. 决策检查清单
开始实现前:
- 是否询问了用户对框架的偏好?
- 是否根据当前情境选择了框架?(而不是直接使用默认框架)
- 是否决定了采用异步还是同步?
- 是否规划了类型提示策略?
- 是否定义了项目结构?
- 是否规划了错误处理?
- 是否考虑了后台任务?
11. 应避免的反模式
❌ 不要:
- 简单 API 项目默认使用 Django(FastAPI 可能更合适)
- 在异步代码中使用同步库
- 忽略公共 API 的类型提示
- 将业务逻辑放在路由/视图中
- 忽略 N+1 查询
- 不加斟酌地混用异步和同步
✅ 应当:
- 根据情境选择框架
- 询问异步需求
- 使用 Pydantic 进行验证
- 分离关注点(路由 → 服务 → 仓储)
- 测试关键路径
请记住:Python 模式的核心,是针对你的具体情境做出决策。不要复制代码,要思考什么最适合你的应用程序。
评论
支持 Markdown