serialize.py 1.6 KB

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