由于本次代码变更内容为空,无法生成有效的提交信息。请提供具体的代码变更内容以便生成合适的提交信息。登录、微信登录等认证功能- 添加管理员登录功能
- 实现个人资料更新和密码修改- 配置数据库连接和 Alembic 迁移 - 添加健康检查和系统统计接口 - 实现自定义错误处理和响应格式 - 配置 FastAPI 应用和中间件
This commit is contained in:
59
fastapi-backend/app/utils/errors.py
Normal file
59
fastapi-backend/app/utils/errors.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
|
||||
class AppError(HTTPException):
|
||||
"""
|
||||
应用程序自定义错误类
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
detail: str,
|
||||
status_code: int = status.HTTP_400_BAD_REQUEST,
|
||||
headers: dict = None
|
||||
):
|
||||
super().__init__(status_code=status_code, detail=detail, headers=headers)
|
||||
|
||||
|
||||
# 常用错误
|
||||
class NotFoundError(AppError):
|
||||
"""
|
||||
资源未找到错误
|
||||
"""
|
||||
def __init__(self, detail: str = "资源未找到"):
|
||||
super().__init__(detail=detail, status_code=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
"""
|
||||
未授权错误
|
||||
"""
|
||||
def __init__(self, detail: str = "未授权"):
|
||||
super().__init__(
|
||||
detail=detail,
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
"""
|
||||
禁止访问错误
|
||||
"""
|
||||
def __init__(self, detail: str = "禁止访问"):
|
||||
super().__init__(detail=detail, status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
class BadRequestError(AppError):
|
||||
"""
|
||||
请求参数错误
|
||||
"""
|
||||
def __init__(self, detail: str = "请求参数错误"):
|
||||
super().__init__(detail=detail, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
"""
|
||||
资源冲突错误
|
||||
"""
|
||||
def __init__(self, detail: str = "资源冲突"):
|
||||
super().__init__(detail=detail, status_code=status.HTTP_409_CONFLICT)
|
||||
43
fastapi-backend/app/utils/response.py
Normal file
43
fastapi-backend/app/utils/response.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
def success_response(
|
||||
data: Any = None,
|
||||
message: Optional[str] = None,
|
||||
code: int = 200
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
标准成功响应格式
|
||||
"""
|
||||
response = {
|
||||
"success": True,
|
||||
"code": code
|
||||
}
|
||||
|
||||
if data is not None:
|
||||
response["data"] = data
|
||||
|
||||
if message:
|
||||
response["message"] = message
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def error_response(
|
||||
message: str,
|
||||
code: int = 400,
|
||||
data: Any = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
标准错误响应格式
|
||||
"""
|
||||
response = {
|
||||
"success": False,
|
||||
"code": code,
|
||||
"message": message
|
||||
}
|
||||
|
||||
if data is not None:
|
||||
response["data"] = data
|
||||
|
||||
return response
|
||||
Reference in New Issue
Block a user