我想从数据类动态创建 Pydantic 模型,类似于如何从数据类动态创建棉花糖模式,如在 marshmallow-dataclass 或 https://stevenloria.com/dynamic-schemas-in-marshmallow/ 中。是否已经有图书馆或简单的方法来做到这一点?
一些背景 - 我更喜欢在我的业务逻辑中使用数据类,而不是直接使用 Pydantic 模型。我使用 Pydantic 模型仅在我的 FastAPI 应用程序中使用驼峰式字段对数据进行序列化/反序列化。但是,我发现自己基本上重复了效率不高的数据类定义。
样本输入:
from typing import List
from dataclasses import dataclass
@dataclass
class Item:
id: int = None
stuff: str = None
height: float = None
@dataclass
class Bag:
id: int = None
name: str = None
things: List[Item] = None
@dataclass
class Basket:
id: int = None
recipient: str = None
bags: List[Bag] = None
best_item: Item = None
所需的输出:
from typing import List
from pydantic.main import BaseModel
def camel_case_converter(value: str):
parts = value.lower().split('_')
return parts[0] + ''.join(i.title() for i in parts[1:])
class CamelBaseModel(BaseModel):
class Config:
alias_generator = camel_case_converter
class Item(CamelBaseModel):
id: int = None
stuff: str = None
height: float = None
class Bag(CamelBaseModel):
id: int = None
name: str = None
things: List[Item] = None
class Basket(CamelBaseModel):
id: int = None
recipient: str = None
bags: List[Bag] = None
best_item: Item = None
答案 0 :(得分:1)
也许是这样的? (来自https://github.com/samuelcolvin/pydantic/issues/1967#issuecomment-742698281)
from typing import Type
from pydantic import BaseModel
from pydantic.dataclasses import dataclass as pydantic_dataclass
from typing import List
from dataclasses import dataclass
def model_from_dataclass(kls: 'StdlibDataclass') -> Type[BaseModel]:
"""Converts a stdlib dataclass to a pydantic BaseModel"""
return pydantic_dataclass(kls).__pydantic_model__
@dataclass
class Item:
id: int = None
stuff: str = None
height: float = None
ItemBaseModel = model_from_dataclass(Item)