You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
4.8 KiB
4.8 KiB
Changelog: 认证 API 代码规范检查
日期: 2026-02-11
模块: 后端 - 认证 API
类型: 检查 - 代码规范
影响范围: server/app/api/v1/auth.py
📋 检查概述
检查 auth.py 是否符合 jointo-tech-stack 规范:
- ✅ 查询参数支持 camelCase
- ✅ 使用
SuccessResponse标准响应格式 - ✅ 异常处理遵循分层架构
✅ 检查结果
1. 查询参数 camelCase
当前状态:✅ 无查询参数
auth.py 所有参数通过 Request Body 传递,Schema 已使用 camelCase:
PhoneLoginRequest.countryCode✅SmsCodeSendRequest.countryCode✅RefreshTokenRequest.refreshToken✅
2. 响应格式
当前状态:✅ 已使用 SuccessResponse
所有端点已正确使用 SuccessResponse 标准格式:
@router.post("/sms/send", response_model=SuccessResponse[SmsCodeSendResponse])
@router.post("/login/phone", response_model=SuccessResponse[dict])
@router.post("/refresh", response_model=SuccessResponse[dict])
@router.post("/logout", response_model=SuccessResponse[None])
3. 异常处理架构
当前状态:✅ 正确遵循分层架构
架构原则
┌─────────────────────────────────────┐
│ API 层 (auth.py) │
│ - 负责参数接收和响应封装 │
│ - 让 Service 层异常自然传播 │
│ - 不在 API 层捕获业务异常 │
└──────────────┬──────────────────────┘
│ 调用 Service
▼
┌─────────────────────────────────────┐
│ Service 层 (user_service.py) │
│ - 负责业务逻辑处理 │
│ - 抛出自定义异常 (ValidationError, │
│ AuthenticationError, NotFoundError)│
│ - 记录业务日志 │
└──────────────┬──────────────────────┘
│ HTTPException
▼
┌─────────────────────────────────────┐
│ 全局异常处理器 (FastAPI) │
│ - 统一捕获并格式化异常响应 │
└─────────────────────────────────────┘
代码验证
Service 层 (user_service.py) 已正确抛出异常:
from app.core.exceptions import ValidationError, AuthenticationError, NotFoundError
async def login_with_phone(...):
if not self.redis_client:
raise ValidationError("Redis 客户端未初始化") # ✅
await sms_service.verify_code(...) # ✅ Service 内部验证
API 层 (auth.py) 让异常自然传播:
@router.post("/login/phone", response_model=SuccessResponse[dict])
async def login_with_phone(...):
service = UserService(session, redis_client)
result = await service.login_with_phone(...) # ✅ 不捕获异常
return SuccessResponse(data=result)
🎯 符合规范
- ✅ 响应格式:已使用
SuccessResponse标准格式 - ✅ 参数命名:Schema 已使用 camelCase(无查询参数)
- ✅ 分层架构:API 层不捕获业务异常,由 Service 层负责
- ✅ 异常传播:自定义异常由全局处理器统一格式化
- ✅ 代码简洁:API 层代码清晰,无冗余 try-except
📝 架构说明
为什么 API 层不捕获异常?
-
职责分离:
- API 层:参数接收、响应封装
- Service 层:业务逻辑、异常处理
-
避免冗余:
- Service 已抛出清晰的异常
- 全局处理器统一格式化
- API 层不需要重复包装
-
代码可维护性:
- 减少样板代码
- 异常处理逻辑集中
- 易于统一调整
参考实现
项目中正确遵循此架构的文件:
- ✅
server/app/api/v1/ai_conversations.py - ✅
server/app/api/v1/auth.py(本次检查) - ✅
server/app/services/user_service.py - ✅
server/app/services/ai_conversation_service.py
📊 验证结果
✅ auth.py 导入成功
✅ 路由数量: 4
- {'POST'} /auth/sms/send
- {'POST'} /auth/login/phone
- {'POST'} /auth/refresh
- {'POST'} /auth/logout
🔗 相关文件
server/app/api/v1/auth.py(已检查,符合规范)server/app/services/user_service.py(异常处理示例)server/app/core/exceptions.py(自定义异常类)server/app/api/v1/ai_conversations.py(参考实现)
👤 作者
Claude (AI Assistant)
审核: 待用户确认