python-backend
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesepython-backend
Python后端开发
Production-ready Python backend patterns for FastAPI, SQLAlchemy, and Upstash.
适用于FastAPI、SQLAlchemy和Upstash的生产级Python后端实践模式。
When to Use This Skill
适用场景
- Building REST APIs with FastAPI
- Implementing JWT/OAuth2 authentication
- Setting up SQLAlchemy async databases
- Integrating Redis/Upstash caching and rate limiting
- Refactoring AI-generated Python code
- Designing API patterns and project structure
- 使用FastAPI构建REST API
- 实现JWT/OAuth2认证
- 搭建SQLAlchemy异步数据库
- 集成Redis/Upstash缓存与限流
- 重构AI生成的Python代码
- 设计API模式与项目结构
Core Principles
核心原则
- Async-first - Use async/await for I/O operations
- Type everything - Pydantic models for validation
- Dependency injection - Use FastAPI's Depends()
- Fail fast - Validate early, use HTTPException
- Security by default - Never trust user input
- 优先异步 - 对I/O操作使用async/await
- 全类型标注 - 使用Pydantic模型进行验证
- 依赖注入 - 使用FastAPI的Depends()
- 快速失败 - 尽早验证,使用HTTPException
- 默认安全 - 绝不信任用户输入
Quick Patterns
快速实践模式
Project Structure
项目结构
src/
├── auth/
│ ├── router.py # endpoints
│ ├── schemas.py # pydantic models
│ ├── models.py # db models
│ ├── service.py # business logic
│ └── dependencies.py
├── posts/
│ └── ...
├── config.py
├── database.py
└── main.pysrc/
├── auth/
│ ├── router.py # 接口端点
│ ├── schemas.py # Pydantic模型
│ ├── models.py # 数据库模型
│ ├── service.py # 业务逻辑
│ └── dependencies.py
├── posts/
│ └── ...
├── config.py
├── database.py
└── main.pyAsync Routes
异步路由
python
undefinedpython
undefinedBAD - blocks event loop
错误示例 - 阻塞事件循环
@router.get("/")
async def bad():
time.sleep(10) # Blocking!
@router.get("/")
async def bad():
time.sleep(10) # 阻塞操作!
GOOD - runs in threadpool
良好示例 - 在线程池中运行
@router.get("/")
def good():
time.sleep(10) # OK in sync function
@router.get("/")
def good():
time.sleep(10) # 在同步函数中允许
BEST - non-blocking
最佳实践 - 非阻塞
@router.get("/")
async def best():
await asyncio.sleep(10) # Non-blocking
undefined@router.get("/")
async def best():
await asyncio.sleep(10) # 非阻塞操作
undefinedPydantic Validation
Pydantic验证
python
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
username: str = Field(min_length=3, max_length=50, pattern="^[a-zA-Z0-9_]+$")
age: int = Field(ge=18)python
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
username: str = Field(min_length=3, max_length=50, pattern="^[a-zA-Z0-9_]+$")
age: int = Field(ge=18)Dependency Injection
依赖注入
python
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
payload = decode_token(token)
user = await get_user(payload["sub"])
if not user:
raise HTTPException(401, "User not found")
return user
@router.get("/me")
async def get_me(user: User = Depends(get_current_user)):
return userpython
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
payload = decode_token(token)
user = await get_user(payload["sub"])
if not user:
raise HTTPException(401, "用户不存在")
return user
@router.get("/me")
async def get_me(user: User = Depends(get_current_user)):
return userSQLAlchemy Async
SQLAlchemy异步实现
python
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield sessionpython
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield sessionRedis Caching
Redis缓存
python
from upstash_redis import Redis
redis = Redis.from_env()
@app.get("/data/{id}")
def get_data(id: str):
cached = redis.get(f"data:{id}")
if cached:
return cached
data = fetch_from_db(id)
redis.setex(f"data:{id}", 600, data)
return datapython
from upstash_redis import Redis
redis = Redis.from_env()
@app.get("/data/{id}")
def get_data(id: str):
cached = redis.get(f"data:{id}")
if cached:
return cached
data = fetch_from_db(id)
redis.setex(f"data:{id}", 600, data)
return dataRate Limiting
限流
python
from upstash_ratelimit import Ratelimit, SlidingWindow
ratelimit = Ratelimit(
redis=Redis.from_env(),
limiter=SlidingWindow(max_requests=10, window=60),
)
@app.get("/api/resource")
def protected(request: Request):
result = ratelimit.limit(request.client.host)
if not result.allowed:
raise HTTPException(429, "Rate limit exceeded")
return {"data": "..."}python
from upstash_ratelimit import Ratelimit, SlidingWindow
ratelimit = Ratelimit(
redis=Redis.from_env(),
limiter=SlidingWindow(max_requests=10, window=60),
)
@app.get("/api/resource")
def protected(request: Request):
result = ratelimit.limit(request.client.host)
if not result.allowed:
raise HTTPException(429, "请求频率超限")
return {"data": "..."}Reference Documents
参考文档
For detailed patterns, see:
| Document | Content |
|---|---|
| Project structure, async, Pydantic, dependencies, testing |
| JWT, OAuth2, password hashing, CORS, API keys |
| SQLAlchemy async, transactions, eager loading, migrations |
| Redis, rate limiting, QStash background jobs |
如需详细实践模式,请参阅:
| 文档 | 内容 |
|---|---|
| 项目结构、异步实现、Pydantic、依赖注入、测试 |
| JWT、OAuth2、密码哈希、CORS、API密钥 |
| SQLAlchemy异步、事务处理、预加载、迁移 |
| Redis、限流、QStash后台任务 |