mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-20 20:39:55 +00:00
style: 统一代码风格和格式 docs: 完善函数和方法的文档字符串 refactor(base_model): 移除冗余的表名和表参数生成方法 refactor(constant): 更新返回码注释格式 refactor(router_class): 添加路由处理器的详细文档 refactor(database): 完善数据库连接函数的文档 refactor(security): 添加认证类和方法的详细文档 refactor(validator): 更新验证器函数的文档格式 refactor(serialize): 优化序列化工具类的文档 refactor(response): 完善响应类的文档字符串 refactor(dependencies): 添加依赖函数的详细文档 refactor(initialize): 完善初始化脚本的文档 refactor(plugin): 添加生命周期和中间件注册的文档 refactor(service): 完善服务层方法的文档 refactor(controller): 添加控制器方法的详细文档 refactor(crud): 完善CRUD操作的文档字符串 refactor(schema): 简化模型类并移除冗余字段 refactor(param): 更新查询参数类的注释格式 refactor(template): 优化代码生成模板的格式 refactor(console): 添加控制台输出功能的实现 refactor(util): 完善工具函数的文档字符串
56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
from pydantic import BaseModel
|
|
from typing import TypeVar, Dict, Any, 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)}")
|
|
|