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.
 
 
 
 
 
 

86 lines
2.6 KiB

"""
统一返回结果类 - 对齐JAVA Result
@author: {{ author }}
@date: {{ date }}
"""
from typing import TypeVar, Generic, Optional, Any
from pydantic import BaseModel, Field
from datetime import datetime
import time
T = TypeVar('T')
class Result(BaseModel, Generic[T]):
"""接口返回数据格式 - 对齐JAVA Result<T>"""
success: bool = Field(True, description="成功标志")
message: str = Field("", description="返回处理消息")
code: int = Field(0, description="返回代码, 0=成功, 500=错误")
result: Optional[T] = Field(None, description="返回数据对象")
timestamp: int = Field(default_factory=lambda: int(time.time() * 1000), description="时间戳")
@staticmethod
def OK(data: Any = None, message: str = "") -> dict:
"""成功返回"""
return {
"success": True,
"message": message,
"code": 200,
"result": data,
"timestamp": int(time.time() * 1000)
}
@staticmethod
def error(message: str, code: int = 500) -> dict:
"""错误返回"""
return {
"success": False,
"message": message,
"code": code,
"result": None,
"timestamp": int(time.time() * 1000)
}
@staticmethod
def noauth(message: str = "无权限访问") -> dict:
"""无权限返回"""
return {
"success": False,
"message": message,
"code": 210,
"result": None,
"timestamp": int(time.time() * 1000)
}
def to_camel_case(name: str) -> str:
"""snake_case 转 camelCase"""
if not name or "_" not in name:
return name
parts = name.split("_")
return parts[0].lower() + "".join(p.capitalize() for p in parts[1:] if p)
def to_camel_dict(obj) -> dict:
"""把 SQLAlchemy 模型实例(或任意对象)转成驼峰 key 的字典。
只提取 __table__.columns 中声明的列,避免泄露 _sa_instance_state 等
SQLAlchemy 内部状态字段。数据库列名是 snake_case,输出 key 转成驼峰。
"""
if obj is None:
return None
if hasattr(obj, "__table__"):
keys = [c.name for c in obj.__table__.columns]
result = {}
for k in keys:
result[to_camel_case(k)] = getattr(obj, k, None)
return result
if isinstance(obj, dict):
return {to_camel_case(k): v for k, v in obj.items()}
if hasattr(obj, "__dict__"):
return {to_camel_case(k): v for k, v in obj.__dict__.items() if not k.startswith("_")}
return obj