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.

56 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from enum import Enum
from typing import Any, Dict, List, Union
# 定义一个枚举类 StateCode用于存储各种状态码
class StateCode(Enum):
SUCCESS = 0
NOT_AUTHORIZED = 1002
PARAMS_ERROR = 1003
USER_NOT_FOUND = 2001
USER_ALREADY_EXISTS = 2002
PASSWORD_INCORRECT = 2003
MOBILE_CODE_ERROR = 2004
ID_CARD_ERROR = 2005
BANK_CARD_ERROR = 2006
MOBILE_ERROR = 2007
ORDER_PAY_ERROR = 3001
STATE_MESSAGES = {
StateCode.SUCCESS: "OK",
StateCode.PARAMS_ERROR: "缺少参数",
StateCode.USER_NOT_FOUND: "用户不存在,操作错误",
StateCode.NOT_AUTHORIZED: "未登录",
StateCode.USER_ALREADY_EXISTS: "用户已存在",
StateCode.PASSWORD_INCORRECT: "用户名或密码错误",
StateCode.MOBILE_CODE_ERROR: "验证码错误",
StateCode.ID_CARD_ERROR: "身份证号验证失败",
StateCode.MOBILE_ERROR: "手机号格式有误",
StateCode.BANK_CARD_ERROR: "银行卡验证错误",
StateCode.ORDER_PAY_ERROR: "支付失败"
}
# 定义一个函数 create_response用于创建统一格式的响应数据
def create_response(
code: StateCode,
message: str = None,
data: Union[Dict[str, Any], List[Dict[str, Any]], Any] = None
) -> Dict[str, Any]:
"""
创建统一的返回格式。
:param code: ErrorCode 错误码
:param message: 错误信息,可选。如果不传递则使用默认的错误信息
:param data: 包含单个或多个 Presenter 转换后的数据。单个使用 dict多个使用 list
:return: 返回统一格式的字典
"""
return {
# 状态码的值
"code": code.value,
# 消息,如果传递了 message 则使用传递的值,否则从 STATE_MESSAGES 中获取默认消息
"msg": message or STATE_MESSAGES.get(code, "Unknown error"),
# 数据
"data": data
}