mcpField
P
python-patterns

python-patterns

github.com/davila7开发33.1k359 次安装1 天前更新
代码仓库

关于 python-patterns

python-patterns 是一项帮助开发者按具体情境制定 Python 设计决策的技能,涵盖框架、异步与同步及项目结构,不要求套用固定模板。

主要功能

  1. 01框架选择指导
  2. 02异步与同步决策
  3. 03类型注解与 Pydantic
  4. 04项目结构原则
  5. 05测试与错误处理

适用场景

  1. 01为新 API 选择框架
  2. 02决定如何处理 I/O 密集型工作
  3. 03规划 Python 项目结构

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/davila7/claude-code-templates --skill python-patterns

安装后在 Claude Code 中输入/python-patterns确认已加载。

详细介绍

Python 模式

2025 年 Python 开发原则与决策。 学会思考,而不是死记硬背模式。


⚠️ 如何使用本技能

本技能教授的是决策原则,而不是可直接复制的固定代码。

  • 当不清楚时,向用户询问框架偏好
  • 根据上下文选择异步还是同步
  • 不要每次都默认使用同一个框架

1. 框架选择(2025)

决策树
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
比较原则
因素FastAPIDjangoFlask
最适合API、微服务全栈、CMS简单、学习
异步原生Django 5.0+通过扩展
管理后台手动内置通过扩展
ORM自行选择Django ORM自行选择
学习曲线低中低
需要提出的选择问题:
  1. 这是仅 API 还是全栈?
  2. 需要管理后台界面吗?
  3. 团队熟悉异步吗?
  4. 有现成的基础设施吗?

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
PostgreSQLasyncpg
Redisaioredis / redis-py async
文件 I/Oaiofiles
数据库 ORMSQLAlchemy 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 原则(2025)

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
E2E完整工作流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