backend-architecture-enforcer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEnforce FastAPI Clean Architecture with BLOCKING validation.
通过阻塞式验证强制实施FastAPI Clean Architecture。
Architecture Overview
架构概述
+-------------------------------------------------------------------+
| ROUTERS LAYER |
| HTTP concerns only: request parsing, response formatting |
| Files: router_*.py, routes_*.py, api_*.py |
+-------------------------------------------------------------------+
| SERVICES LAYER |
| Business logic: orchestration, validation, transformations |
| Files: *_service.py |
+-------------------------------------------------------------------+
| REPOSITORIES LAYER |
| Data access: database queries, external API calls |
| Files: *_repository.py, *_repo.py |
+-------------------------------------------------------------------+
| MODELS LAYER |
| Data structures: SQLAlchemy models, Pydantic schemas |
| Files: *_model.py (ORM), *_schema.py (Pydantic) |
+-------------------------------------------------------------------++-------------------------------------------------------------------+
| 路由器层 (ROUTERS LAYER) |
| 仅处理HTTP相关事宜:请求解析、响应格式化 |
| 文件:router_*.py, routes_*.py, api_*.py |
+-------------------------------------------------------------------+
| 服务层 (SERVICES LAYER) |
| 业务逻辑:编排、验证、数据转换 |
| 文件:*_service.py |
+-------------------------------------------------------------------+
| 仓库层 (REPOSITORIES LAYER) |
| 数据访问:数据库查询、外部API调用 |
| 文件:*_repository.py, *_repo.py |
+-------------------------------------------------------------------+
| 模型层 (MODELS LAYER) |
| 数据结构:SQLAlchemy模型、Pydantic schemas |
| 文件:*_model.py (ORM), *_schema.py (Pydantic) |
+-------------------------------------------------------------------+Validation Rules (BLOCKING)
验证规则(阻塞式)
| Rule | Check | Layer |
|---|---|---|
| No DB in Routers | Database operations blocked | routers/ |
| No HTTP in Services | HTTPException blocked | services/ |
| No Business Logic in Routers | Complex logic blocked | routers/ |
| Use Depends() | Direct instantiation blocked | routers/ |
| Async Consistency | Sync calls in async blocked | all |
| File Naming | Must follow naming convention | all |
| 规则 | 检查内容 | 层级 |
|---|---|---|
| 路由器层禁止数据库操作 | 数据库操作被阻止 | routers/ |
| 服务层禁止HTTP操作 | HTTPException被阻止 | services/ |
| 路由器层禁止业务逻辑 | 复杂逻辑被阻止 | routers/ |
| 必须使用Depends() | 直接实例化被阻止 | routers/ |
| 异步一致性 | 异步代码中的同步调用被阻止 | 所有层级 |
| 文件命名规范 | 必须遵循命名约定 | 所有层级 |
File Naming Conventions
文件命名规范
Quick Reference
速查参考
| Layer | Allowed Patterns | Blocked Patterns |
|---|---|---|
| Routers | | |
| Services | | |
| Repositories | | |
| Schemas | | |
| Models | | |
| 层级 | 允许的命名模式 | 禁止的命名模式 |
|---|---|---|
| 路由器层 | | |
| 服务层 | | |
| 仓库层 | | |
| Schema层 | | |
| 模型层 | | |
Layer Separation Summary
分层总结
Routers (HTTP Only)
路由器层(仅处理HTTP)
- Request parsing and response formatting
- HTTP status codes and auth checks
- Delegate to services via
Depends()
- 请求解析与响应格式化
- HTTP状态码与权限校验
- 通过委托给服务层处理
Depends()
Services (Business Logic)
服务层(业务逻辑)
- Validation and orchestration
- Data transformations
- Raise domain exceptions (NOT HTTPException)
- 验证与编排
- 数据转换
- 抛出领域异常(禁止使用HTTPException)
Repositories (Data Access)
仓库层(数据访问)
- Database queries and persistence
- External API calls
- Return domain objects or None
- 数据库查询与持久化
- 外部API调用
- 返回领域对象或None
Dependency Injection Quick Reference
依赖注入速查
python
undefinedpython
undefineddeps.py - Dependency providers
deps.py - 依赖提供者
def get_user_repository(
db: AsyncSession = Depends(get_db),
) -> UserRepository:
return UserRepository(db)
def get_user_service(
repo: UserRepository = Depends(get_user_repository),
) -> UserService:
return UserService(repo)
def get_user_repository(
db: AsyncSession = Depends(get_db),
) -> UserRepository:
return UserRepository(db)
def get_user_service(
repo: UserRepository = Depends(get_user_repository),
) -> UserService:
return UserService(repo)
router_users.py - Usage
router_users.py - 使用示例
@router.get("/{user_id}")
async def get_user(
user_id: int,
service: UserService = Depends(get_user_service),
):
return await service.get_user(user_id)
undefined@router.get("/{user_id}")
async def get_user(
user_id: int,
service: UserService = Depends(get_user_service),
):
return await service.get_user(user_id)
undefinedBlocked DI Patterns
被禁止的依赖注入模式
python
undefinedpython
undefinedBLOCKED - Direct instantiation
禁止 - 直接实例化
service = UserService()
service = UserService()
BLOCKED - Global instance
禁止 - 全局实例
user_service = UserService()
user_service = UserService()
BLOCKED - Missing Depends()
禁止 - 缺少Depends()
async def get_users(db: AsyncSession): # Missing Depends()
undefinedasync def get_users(db: AsyncSession): # 缺少Depends()
undefinedCommon Violations
常见违规情况
| Violation | Detection | Fix |
|---|---|---|
| DB in router | | Move to repository |
| HTTPException in service | | Use domain exceptions |
| Direct instantiation | | Use |
| Wrong naming | Missing suffix/prefix | Rename per convention |
| Sync in async | Missing | Add |
| 违规内容 | 检测方式 | 修复方案 |
|---|---|---|
| 路由器层存在数据库操作 | 在routers/目录中检测到 | 迁移至仓库层处理 |
| 服务层抛出HTTPException | 在services/目录中检测到 | 使用领域异常替代 |
| 直接实例化服务 | 未通过Depends()创建 | 使用 |
| 命名不符合规范 | 缺少指定后缀/前缀 | 按照约定重命名文件 |
| 异步代码中存在同步调用 | 缺少 | 添加 |
Exception Pattern
异常模式
python
undefinedpython
undefinedDomain exceptions (services/repositories)
领域异常(服务层/仓库层)
class UserNotFoundError(DomainException):
def init(self, user_id: int):
super().init(f"User {user_id} not found")
class UserNotFoundError(DomainException):
def init(self, user_id: int):
super().init(f"User {user_id} not found")
Router converts to HTTP
路由器层转换为HTTP异常
@router.get("/{user_id}")
async def get_user(user_id: int, service: UserService = Depends(get_user_service)):
try:
return await service.get_user(user_id)
except UserNotFoundError:
raise HTTPException(404, "User not found")
undefined@router.get("/{user_id}")
async def get_user(user_id: int, service: UserService = Depends(get_user_service)):
try:
return await service.get_user(user_id)
except UserNotFoundError:
raise HTTPException(404, "User not found")
undefinedAsync Rules
异步规则
python
undefinedpython
undefinedGOOD - Async all the way
正确 - 全程异步
result = await db.execute(select(User))
result = await db.execute(select(User))
BLOCKED - Sync in async function
禁止 - 异步函数中使用同步调用
result = db.execute(select(User)) # Missing await
result = db.execute(select(User)) # 缺少await
For sync code, use executor
对于同步代码,使用执行器
await loop.run_in_executor(None, sync_function)
undefinedawait loop.run_in_executor(None, sync_function)
undefinedReferences
参考资料
For detailed patterns and examples, see:
| Reference | Content |
|---|---|
| layer-rules.md | Detailed layer separation rules with code examples |
| dependency-injection.md | DI patterns, authentication, testing with overrides |
| violation-examples.md | Common violations with proper patterns and auto-fix suggestions |
如需详细模式与示例,请查看:
| 参考文档 | 内容 |
|---|---|
| layer-rules.md | 包含代码示例的详细分层规则 |
| dependency-injection.md | 依赖注入模式、认证、测试覆盖 |
| violation-examples.md | 常见违规场景、正确模式及自动修复建议 |
Related Skills
相关技能
- - DDD patterns
clean-architecture - - Advanced FastAPI patterns
fastapi-advanced - - DI patterns
dependency-injection - - Folder structure
project-structure-enforcer
- - 领域驱动设计模式
clean-architecture - - 高级FastAPI模式
fastapi-advanced - - 依赖注入模式
dependency-injection - - 项目结构规范
project-structure-enforcer
Capability Details
功能详情
layer-separation
layer-separation
Keywords: router, service, repository, layer, clean architecture, separation
Solves:
- Prevent database operations in routers
- Block business logic in route handlers
- Ensure proper layer boundaries
关键词: router, service, repository, layer, clean architecture, separation
解决问题:
- 防止路由器层执行数据库操作
- 阻止路由处理器中包含业务逻辑
- 确保合理的层级边界
dependency-injection
dependency-injection
Keywords: depends, dependency injection, DI, fastapi depends, inject
Solves:
- Enforce use of FastAPI Depends() pattern
- Block direct instantiation in routers
- Ensure testable code structure
关键词: depends, dependency injection, DI, fastapi depends, inject
解决问题:
- 强制使用FastAPI Depends()模式
- 阻止路由器层直接实例化对象
- 确保代码结构可测试
file-naming
file-naming
Keywords: naming convention, file name, router_, _service, _repository
Solves:
- Enforce consistent file naming patterns
- Validate router/service/repository naming
- Maintain codebase consistency
关键词: naming convention, file name, router_, _service, _repository
解决问题:
- 强制统一的文件命名模式
- 验证路由器/服务/仓库的命名规范
- 维护代码库一致性
async-patterns
async-patterns
Keywords: async, await, sync, blocking call, asyncio
Solves:
- Detect sync calls in async functions
- Prevent blocking operations in async code
- Ensure async consistency
关键词: async, await, sync, blocking call, asyncio
解决问题:
- 检测异步函数中的同步调用
- 防止异步代码中出现阻塞操作
- 确保异步一致性