mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-21 04:46:26 +00:00
refactor: 统一状态字段为字符串类型并更新相关组件 refactor: 更新模型基类移除租户和客户相关字段 refactor: 简化数据权限控制逻辑 refactor: 优化类型注解使用Python 3.10+语法 refactor: 清理无用导入和注释 docs: 更新文档移除多租户相关内容
56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
from pydantic import BaseModel
|
|
from typing import Any, TypeVar, Type, Generic
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
|
|
ModelType = TypeVar("ModelType", bound=DeclarativeBase)
|
|
SchemaType = TypeVar("SchemaType", bound=BaseModel)
|
|
|
|
|
|
class Serialize(Generic[ModelType, SchemaType]):
|
|
"""
|
|
序列化工具类,提供模型、Schema 和字典之间的转换功能
|
|
"""
|
|
|
|
@classmethod
|
|
def schema_to_model(cls,schema: Type[SchemaType], model: Type[ModelType]) -> ModelType:
|
|
"""
|
|
将 Pydantic Schema 转换为 SQLAlchemy 模型
|
|
|
|
参数:
|
|
- schema (Type[SchemaType]): Pydantic Schema 实例。
|
|
- model (Type[ModelType]): SQLAlchemy 模型类。
|
|
|
|
返回:
|
|
- ModelType: SQLAlchemy 模型实例。
|
|
|
|
异常:
|
|
- ValueError: 转换过程中可能抛出的异常。
|
|
"""
|
|
try:
|
|
return model(**cls.model_to_dict(model, schema))
|
|
except Exception as e:
|
|
raise ValueError(f"序列化失败: {str(e)}")
|
|
|
|
@classmethod
|
|
def model_to_dict(cls, model: Type[ModelType], schema: Type[SchemaType]) -> dict[str, Any]:
|
|
"""
|
|
将 SQLAlchemy 模型转换为 Pydantic Schema
|
|
|
|
参数:
|
|
- model (Type[ModelType]): SQLAlchemy 模型实例。
|
|
- schema (Type[SchemaType]): Pydantic Schema 类。
|
|
|
|
返回:
|
|
- dict[str, Any]: 包含模型数据的字典。
|
|
|
|
异常:
|
|
- ValueError: 转换过程中可能抛出的异常。
|
|
"""
|
|
try:
|
|
return schema.model_validate(model).model_dump()
|
|
except Exception as e:
|
|
raise ValueError(f"反序列化失败: {str(e)}")
|
|
|