serialize.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. from pydantic import BaseModel
  3. from typing import Any, TypeVar, Type, Generic
  4. from sqlalchemy.orm import DeclarativeBase
  5. ModelType = TypeVar("ModelType", bound=DeclarativeBase)
  6. SchemaType = TypeVar("SchemaType", bound=BaseModel)
  7. class Serialize(Generic[ModelType, SchemaType]):
  8. """
  9. 序列化工具类,提供模型、Schema 和字典之间的转换功能
  10. """
  11. @classmethod
  12. def schema_to_model(cls,schema: Type[SchemaType], model: Type[ModelType]) -> ModelType:
  13. """
  14. 将 Pydantic Schema 转换为 SQLAlchemy 模型
  15. 参数:
  16. - schema (Type[SchemaType]): Pydantic Schema 实例。
  17. - model (Type[ModelType]): SQLAlchemy 模型类。
  18. 返回:
  19. - ModelType: SQLAlchemy 模型实例。
  20. 异常:
  21. - ValueError: 转换过程中可能抛出的异常。
  22. """
  23. try:
  24. return model(**cls.model_to_dict(model, schema))
  25. except Exception as e:
  26. raise ValueError(f"序列化失败: {str(e)}")
  27. @classmethod
  28. def model_to_dict(cls, model: Type[ModelType], schema: Type[SchemaType]) -> dict[str, Any]:
  29. """
  30. 将 SQLAlchemy 模型转换为 Pydantic Schema
  31. 参数:
  32. - model (Type[ModelType]): SQLAlchemy 模型实例。
  33. - schema (Type[SchemaType]): Pydantic Schema 类。
  34. 返回:
  35. - dict[str, Any]: 包含模型数据的字典。
  36. 异常:
  37. - ValueError: 转换过程中可能抛出的异常。
  38. """
  39. try:
  40. return schema.model_validate(model).model_dump()
  41. except Exception as e:
  42. raise ValueError(f"反序列化失败: {str(e)}")