68 lines
1.7 KiB
Python
68 lines
1.7 KiB
Python
from fastapi import APIRouter, Request, Depends, HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
from typing import Dict, Any, Optional
|
|
from datetime import datetime
|
|
from config.error_messages import HTTP_ERROR_MESSAGES, BUSINESS_ERROR_MESSAGES
|
|
import logging
|
|
|
|
# 设置日志
|
|
logger = logging.getLogger("app.api")
|
|
|
|
router = APIRouter(
|
|
prefix="/api/common",
|
|
tags=["通用接口"]
|
|
)
|
|
|
|
@router.get("/health")
|
|
async def health_check():
|
|
"""健康检查接口"""
|
|
return {
|
|
"status": "ok",
|
|
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|
"message": "系统运行正常"
|
|
}
|
|
|
|
@router.get("/error-codes")
|
|
async def get_error_codes():
|
|
"""获取系统定义的错误码说明"""
|
|
return {
|
|
"http_errors": HTTP_ERROR_MESSAGES,
|
|
"business_errors": BUSINESS_ERROR_MESSAGES
|
|
}
|
|
|
|
# 通用响应格式化函数
|
|
def format_response(data: Any = None, message: str = "操作成功", code: int = 200) -> Dict:
|
|
"""
|
|
统一API响应格式
|
|
|
|
Args:
|
|
data: 响应数据
|
|
message: 响应消息
|
|
code: 响应码
|
|
|
|
Returns:
|
|
统一格式的响应字典
|
|
"""
|
|
return {
|
|
"code": code,
|
|
"message": message,
|
|
"data": data
|
|
}
|
|
|
|
# 通用错误响应
|
|
def error_response(message: str, code: int = 400, data: Optional[Any] = None) -> JSONResponse:
|
|
"""
|
|
统一错误响应格式
|
|
|
|
Args:
|
|
message: 错误消息
|
|
code: 错误码
|
|
data: 错误详情数据
|
|
|
|
Returns:
|
|
JSONResponse对象
|
|
"""
|
|
return JSONResponse(
|
|
status_code=code,
|
|
content=format_response(data=data, message=message, code=code)
|
|
) |