python-backend-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Backend Development Standards

Python 后端开发标准

Architecture Overview

架构概述

Router/Controller → Service → Repository → Database
      ↓                ↓            ↓
   Schemas         Business      SQLAlchemy
  (Pydantic)        Logic         Models
Router/Controller → Service → Repository → Database
      ↓                ↓            ↓
   Schemas         Business      SQLAlchemy
  (Pydantic)        Logic         Models

Layer Responsibilities

层级职责

LayerLocationPurpose
Models
app/models/
SQLAlchemy ORM, database schema
Schemas
app/schemas/
Pydantic DTOs (request/response)
Repositories
app/repositories/
Database CRUD operations
Services
app/services/
Business logic orchestration
Controllers
app/api/v1/
FastAPI routes, thin handlers
Migrations
alembic/versions/
Database migrations
层级存放路径职责
Models
app/models/
SQLAlchemy ORM,数据库 schema
Schemas
app/schemas/
Pydantic DTO(请求/响应)
Repositories
app/repositories/
数据库CRUD操作
Services
app/services/
业务逻辑编排
Controllers
app/api/v1/
FastAPI路由,轻量处理器
Migrations
alembic/versions/
数据库迁移

Naming Conventions

命名规范

Files

文件命名

  • All lowercase with underscores:
    user_profile.py
  • One entity per file
  • Match filename to class:
    user.py
    class User
  • 全部小写并使用下划线:
    user_profile.py
  • 每个文件对应一个实体
  • 文件名与类名匹配:
    user.py
    class User

Classes

类命名

  • Models:
    User
    ,
    BlogPost
    (PascalCase, singular)
  • Schemas:
    UserCreate
    ,
    UserResponse
    ,
    UserUpdate
  • Repositories:
    UserRepository
  • Services:
    UserService
  • 模型:
    User
    BlogPost
    (大驼峰命名,单数形式)
  • Schemas:
    UserCreate
    UserResponse
    UserUpdate
  • 仓库:
    UserRepository
  • 服务:
    UserService

Database

数据库命名

  • Table names: plural snake_case (
    users
    ,
    blog_posts
    )
  • Column names: snake_case (
    created_at
    ,
    user_id
    )
  • 表名:复数形式蛇形命名(
    users
    blog_posts
  • 列名:蛇形命名(
    created_at
    user_id

Alembic Migrations

Alembic 迁移规范

File Naming Convention

文件命名格式

yyyymmdd_HHmm_<feature>.py
Examples:
  • 20260117_0930_create_users_table.py
  • 20260117_1045_add_email_to_users.py
  • 20260117_1400_create_api_keys_table.py
yyyymmdd_HHmm_<feature>.py
示例:
  • 20260117_0930_create_users_table.py
  • 20260117_1045_add_email_to_users.py
  • 20260117_1400_create_api_keys_table.py

Create Migration Command

创建迁移命令

bash
undefined
bash
undefined

Generate with autogenerate

自动生成迁移文件

alembic revision --autogenerate -m "description"
alembic revision --autogenerate -m "description"

Then rename the file to follow convention:

随后按照规范重命名文件:

FROM: xxxx_description.py

原文件名:xxxx_description.py

TO: yyyymmdd_HHmm_description.py

新文件名:yyyymmdd_HHmm_description.py

undefined
undefined

Code Standards

代码规范

Async Everything

全异步实现

  • All database operations must be async
  • Use
    async def
    for all handlers, services, repositories
  • Use
    await
    for all I/O operations
  • 所有数据库操作必须为异步
  • 所有处理器、服务、仓库均使用
    async def
    定义
  • 所有I/O操作均使用
    await

Dependency Injection

依赖注入

  • Use FastAPI
    Depends()
    for dependencies
  • Inject database sessions into services
  • Services inject repositories
  • 使用FastAPI的
    Depends()
    实现依赖注入
  • 向服务中注入数据库会话
  • 服务中注入仓库实例

Error Handling

错误处理

  • Use custom exceptions in
    app/core/exceptions.py
  • Let FastAPI exception handlers convert to HTTP responses
  • Never catch and swallow exceptions silently
  • app/core/exceptions.py
    中定义自定义异常
  • 由FastAPI异常处理器转换为HTTP响应
  • 禁止静默捕获并忽略异常

Security

安全规范

  • Argon2id for password hashing
  • Parameterized queries (SQLAlchemy ORM)
  • Input validation (Pydantic)
  • Rate limiting on auth endpoints
  • 使用Argon2id进行密码哈希
  • 使用参数化查询(SQLAlchemy ORM)
  • 输入验证(Pydantic)
  • 对认证端点进行速率限制

Reference Navigation

参考导航

Core Patterns:
  • python-models.md - SQLAlchemy ORM (User, ApiKey)
  • python-schemas.md - Pydantic v2 patterns
  • python-repositories.md - Repository pattern
  • python-services.md - Service layer patterns
  • python-api-design.md - FastAPI routes and controllers
  • python-migrations.md - Alembic migration patterns
  • python-utils.md - Utility functions (datetime, string, validation)
Security & Auth:
  • python-authentication.md - JWT, API Keys, OAuth
  • python-middleware.md - Dual auth, rate limiting, credits
  • python-security.md - OWASP Top 10, input validation
Quality & Operations:
  • python-testing.md - pytest patterns, fixtures
  • python-performance.md - Caching, query optimization, async
  • python-debugging.md - Logging, profiling, error tracking
  • python-devops.md - Docker, CI/CD, deployment
核心模式:
  • python-models.md - SQLAlchemy ORM(用户、ApiKey)
  • python-schemas.md - Pydantic v2 模式
  • python-repositories.md - 仓库模式
  • python-services.md - 服务层模式
  • python-api-design.md - FastAPI路由与控制器
  • python-migrations.md - Alembic迁移模式
  • python-utils.md - 工具函数(日期时间、字符串、验证)
安全与认证:
  • python-authentication.md - JWT、API密钥、OAuth
  • python-middleware.md - 双重认证、速率限制、额度管控
  • python-security.md - OWASP Top 10、输入验证
质量与运维:
  • python-testing.md - pytest模式、夹具
  • python-performance.md - 缓存、查询优化、异步
  • python-debugging.md - 日志、性能分析、错误追踪
  • python-devops.md - Docker、CI/CD、部署