backend-architecture-enforcer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Enforce 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)

验证规则(阻塞式)

RuleCheckLayer
No DB in RoutersDatabase operations blockedrouters/
No HTTP in ServicesHTTPException blockedservices/
No Business Logic in RoutersComplex logic blockedrouters/
Use Depends()Direct instantiation blockedrouters/
Async ConsistencySync calls in async blockedall
File NamingMust follow naming conventionall
规则检查内容层级
路由器层禁止数据库操作数据库操作被阻止routers/
服务层禁止HTTP操作HTTPException被阻止services/
路由器层禁止业务逻辑复杂逻辑被阻止routers/
必须使用Depends()直接实例化被阻止routers/
异步一致性异步代码中的同步调用被阻止所有层级
文件命名规范必须遵循命名约定所有层级

File Naming Conventions

文件命名规范

Quick Reference

速查参考

LayerAllowed PatternsBlocked Patterns
Routers
router_*.py
,
routes_*.py
,
api_*.py
,
deps.py
users.py
,
UserRouter.py
Services
*_service.py
users.py
,
UserService.py
,
service_*.py
Repositories
*_repository.py
,
*_repo.py
users.py
,
repository_*.py
Schemas
*_schema.py
,
*_dto.py
,
*_request.py
,
*_response.py
users.py
,
UserSchema.py
Models
*_model.py
,
*_entity.py
,
*_orm.py
,
base.py
users.py
,
UserModel.py
层级允许的命名模式禁止的命名模式
路由器层
router_*.py
,
routes_*.py
,
api_*.py
,
deps.py
users.py
,
UserRouter.py
服务层
*_service.py
users.py
,
UserService.py
,
service_*.py
仓库层
*_repository.py
,
*_repo.py
users.py
,
repository_*.py
Schema层
*_schema.py
,
*_dto.py
,
*_request.py
,
*_response.py
users.py
,
UserSchema.py
模型层
*_model.py
,
*_entity.py
,
*_orm.py
,
base.py
users.py
,
UserModel.py

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
undefined
python
undefined

deps.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)
undefined

Blocked DI Patterns

被禁止的依赖注入模式

python
undefined
python
undefined

BLOCKED - 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()
undefined
async def get_users(db: AsyncSession): # 缺少Depends()
undefined

Common Violations

常见违规情况

ViolationDetectionFix
DB in router
db.add
,
db.execute
in routers/
Move to repository
HTTPException in service
raise HTTPException
in services/
Use domain exceptions
Direct instantiation
Service()
without Depends
Use
Depends(get_service)
Wrong namingMissing suffix/prefixRename per convention
Sync in asyncMissing
await
Add
await
or use executor
违规内容检测方式修复方案
路由器层存在数据库操作在routers/目录中检测到
db.add
db.execute
迁移至仓库层处理
服务层抛出HTTPException在services/目录中检测到
raise HTTPException
使用领域异常替代
直接实例化服务未通过Depends()创建
Service()
实例
使用
Depends(get_service)
替代
命名不符合规范缺少指定后缀/前缀按照约定重命名文件
异步代码中存在同步调用缺少
await
关键字
添加
await
或使用执行器

Exception Pattern

异常模式

python
undefined
python
undefined

Domain 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")
undefined

Async Rules

异步规则

python
undefined
python
undefined

GOOD - 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)
undefined
await loop.run_in_executor(None, sync_function)
undefined

References

参考资料

For detailed patterns and examples, see:
ReferenceContent
layer-rules.mdDetailed layer separation rules with code examples
dependency-injection.mdDI patterns, authentication, testing with overrides
violation-examples.mdCommon violations with proper patterns and auto-fix suggestions
如需详细模式与示例,请查看:
参考文档内容
layer-rules.md包含代码示例的详细分层规则
dependency-injection.md依赖注入模式、认证、测试覆盖
violation-examples.md常见违规场景、正确模式及自动修复建议

Related Skills

相关技能

  • clean-architecture
    - DDD patterns
  • fastapi-advanced
    - Advanced FastAPI patterns
  • dependency-injection
    - DI patterns
  • project-structure-enforcer
    - Folder structure
  • clean-architecture
    - 领域驱动设计模式
  • fastapi-advanced
    - 高级FastAPI模式
  • 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 解决问题:
  • 检测异步函数中的同步调用
  • 防止异步代码中出现阻塞操作
  • 确保异步一致性