feat: 初始化仓库

This commit is contained in:
2025-02-12 02:38:29 +08:00
commit 46e9e79670
67 changed files with 8960 additions and 0 deletions

7
exceptions/__init__.py Normal file
View File

@@ -0,0 +1,7 @@
# _*_ coding : UTF-8 _*_
# @Time : 2025/01/18 01:58
# @UpdateTime : 2025/01/18 01:58
# @Author : sonder
# @File : __init__.py.py
# @Software : PyCharm
# @Comment : 本程序

162
exceptions/exception.py Normal file
View File

@@ -0,0 +1,162 @@
# _*_ coding : UTF-8 _*_
# @Time : 2025/01/18 02:21
# @UpdateTime : 2025/01/18 02:21
# @Author : sonder
# @File : exception.py
# @Software : PyCharm
# @Comment : 本程序
from typing import Optional, Any
from fastapi.responses import JSONResponse
from utils.response import Response
class LoginException(Exception):
"""
自定义登录异常。
- 用于处理登录相关的异常情况。
"""
def __init__(self, message: str = "登录失败", data: Optional[Any] = None):
"""
初始化登录异常。
:param message: 异常消息,默认为 "登录失败"
:param data: 异常相关的数据
"""
self.message = message
self.data = data
def to_response(self) -> JSONResponse:
"""
将异常转换为统一的响应格式。
:return: JSONResponse 对象
"""
return Response.failure(msg=self.message, data=self.data)
class AuthException(Exception):
"""
自定义令牌异常。
- 用于处理身份验证相关的异常情况。
"""
def __init__(self, message: str = "身份验证失败", data: Optional[Any] = None):
"""
初始化令牌异常。
:param message: 异常消息,默认为 "身份验证失败"
:param data: 异常相关的数据
"""
self.message = message
self.data = data
def to_response(self) -> JSONResponse:
"""
将异常转换为统一的响应格式。
:return: JSONResponse 对象
"""
return Response.unauthorized(msg=self.message, data=self.data)
class PermissionException(Exception):
"""
自定义权限异常。
- 用于处理权限相关的异常情况。
"""
def __init__(self, message: str = "权限不足", data: Optional[Any] = None):
"""
初始化权限异常。
:param message: 异常消息,默认为 "权限不足"
:param data: 异常相关的数据
"""
self.message = message
self.data = data
def to_response(self) -> JSONResponse:
"""
将异常转换为统一的响应格式。
:return: JSONResponse 对象
"""
return Response.forbidden(msg=self.message, data=self.data)
class ServiceException(Exception):
"""
自定义服务异常。
- 用于处理服务层逻辑相关的异常情况。
"""
def __init__(self, message: str = "服务异常", data: Optional[Any] = None):
"""
初始化服务异常。
:param message: 异常消息,默认为 "服务异常"
:param data: 异常相关的数据
"""
self.message = message
self.data = data
def to_response(self) -> JSONResponse:
"""
将异常转换为统一的响应格式。
:return: JSONResponse 对象
"""
return Response.error(msg=self.message, data=self.data)
class ServiceWarning(Exception):
"""
自定义服务警告。
- 用于处理服务层逻辑中的警告情况(非致命错误)。
"""
def __init__(self, message: str = "服务警告", data: Optional[Any] = None):
"""
初始化服务警告。
:param message: 警告消息,默认为 "服务警告"
:param data: 警告相关的数据
"""
self.message = message
self.data = data
def to_response(self) -> JSONResponse:
"""
将警告转换为统一的响应格式。
:return: JSONResponse 对象
"""
return Response.failure(msg=self.message, data=self.data)
class ModelValidatorException(Exception):
"""
自定义模型校验异常。
- 用于处理数据模型校验失败的异常情况。
"""
def __init__(self, message: str = "数据校验失败", data: Optional[Any] = None):
"""
初始化模型校验异常。
:param message: 异常消息,默认为 "数据校验失败"
:param data: 异常相关的数据
"""
self.message = message
self.data = data
def to_response(self) -> JSONResponse:
"""
将异常转换为统一的响应格式。
:return: JSONResponse 对象
"""
return Response.failure(msg=self.message, data=self.data)

134
exceptions/handle.py Normal file
View File

@@ -0,0 +1,134 @@
# _*_ coding : UTF-8 _*_
# @Time : 2025/01/18 02:24
# @UpdateTime : 2025/01/18 02:24
# @Author : sonder
# @File : handle.py
# @Software : PyCharm
# @Comment : 本程序
from fastapi import FastAPI, Request
from fastapi.exceptions import HTTPException
from pydantic_validation_decorator import FieldValidationError
from starlette.responses import JSONResponse
from exceptions.exception import (
AuthException,
LoginException,
ModelValidatorException,
PermissionException,
ServiceException,
ServiceWarning,
)
from utils.log import logger
from utils.response import Response
def handle_exception(app: FastAPI):
"""
全局异常处理拦截器。
- 捕获并处理所有异常,返回统一的接口响应格式。
"""
@app.exception_handler(AuthException)
async def auth_exception_handler(request: Request, exc: AuthException):
"""
处理自定义身份验证异常AuthException
- 返回 401 未授权响应。
"""
logger.warning(f"身份验证异常: {exc.message}")
return Response.unauthorized(data=exc.data, msg=exc.message)
@app.exception_handler(LoginException)
async def login_exception_handler(request: Request, exc: LoginException):
"""
处理自定义登录异常LoginException
- 返回 400 失败响应。
"""
logger.warning(f"登录异常: {exc.message}")
return Response.failure(data=exc.data, msg=exc.message)
@app.exception_handler(ModelValidatorException)
async def model_validator_exception_handler(request: Request, exc: ModelValidatorException):
"""
处理自定义模型校验异常ModelValidatorException
- 返回 400 失败响应。
"""
logger.warning(f"模型校验异常: {exc.message}")
return Response.failure(data=exc.data, msg=exc.message)
@app.exception_handler(FieldValidationError)
async def field_validation_error_handler(request: Request, exc: FieldValidationError):
"""
处理字段校验异常FieldValidationError
- 返回 400 失败响应。
"""
logger.warning(f"字段校验异常: {exc.message}")
return Response.failure(msg=exc.message)
@app.exception_handler(PermissionException)
async def permission_exception_handler(request: Request, exc: PermissionException):
"""
处理自定义权限异常PermissionException
- 返回 403 未授权响应。
"""
logger.warning(f"权限异常: {exc.message}")
return Response.forbidden(data=exc.data, msg=exc.message)
@app.exception_handler(ServiceException)
async def service_exception_handler(request: Request, exc: ServiceException):
"""
处理自定义服务异常ServiceException
- 返回 500 错误响应。
"""
logger.error(f"服务异常: {exc.message}")
return Response.error(data=exc.data, msg=exc.message)
@app.exception_handler(ServiceWarning)
async def service_warning_handler(request: Request, exc: ServiceWarning):
"""
处理自定义服务警告ServiceWarning
- 返回 400 失败响应。
"""
logger.warning(f"服务警告: {exc.message}")
return Response.failure(data=exc.data, msg=exc.message)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""
处理 FastAPI 的 HTTP 异常。
- 返回统一的错误响应格式。
"""
logger.warning(f"HTTP 异常: {exc.detail}")
return Response.failure(msg=exc.detail)
@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception):
"""
处理其他未捕获的异常。
- 返回 500 错误响应。
"""
logger.exception(f"未捕获的异常: {str(exc)}")
return Response.error(msg="服务器内部错误")
@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc: HTTPException):
"""
处理 404 未找到资源异常。
- 返回 404 失败响应。
"""
logger.warning(f"404 异常: {request.url} 未找到")
return JSONResponse(
content={"code": 404, "msg": "无效路径!", "data": None},
status_code=404,
)
@app.exception_handler(405)
async def method_not_allowed_handler(request: Request, exc: HTTPException):
"""
处理 405 方法不允许异常。
- 返回 405 失败响应。
"""
logger.warning(f"405 异常: {request.method} 方法不允许")
return JSONResponse(
status_code=405,
content={"code": 405, "msg": "请求方法错误", "data": None},
)