"""结构化数据模型处理
基于 Pydantic 的 BaseModel 构建的结构化层次模型,可以用于描述层次关系数据结构
与嵌套字典的区别:
可以通过点号访问属性
自动参数验证
"""
from typing import Union, List, Optional
from pydantic import BaseModel, FilePath, AnyUrl, Field
def _save(filename, data):
with open(filename, "w", encoding='utf-8') as fp:
fp.write(
data
)
class SharedModel(BaseModel):
name: str
icon: Optional[Union[FilePath, AnyUrl]] = None
desc: str = Field("")
class Item(SharedModel):
link: AnyUrl | str
class Group(SharedModel):
items: List[Item]
def save(self, filename):
_save(filename, self.json(ensure_ascii=False))
class Collection(BaseModel):
name: str
groups: List[Group] = Field(default_factory=list, description="项目合集")
def save(self, filename):
_save(
filename,
self.json(ensure_ascii=False, indent=4)
)
def __iter__(self):
"""迭代所有分组
:return: Group
"""
for group in self.groups:
yield group
def __getitem__(self, group_name):
for group in self.groups:
if group.name == group_name:
return group
raise KeyError(f"Not find {group_name} in Collection({self.name})")
collection = Collection(name="收集", groups=[
Group(name="Abc", desc="bbq", items=[
Item(name="setuptools", desc="打包工具", link="https://peps.python.org/pep-0518/#toml")
])
])
if __name__ == '__main__':
collection.save("abc.json")
new_collection = Collection.parse_file("abc.json")
使用 Pydantic 描述层次数据结构
最新推荐文章于 2024-08-14 23:13:27 发布