如何使用 Pydantic 验证复杂的嵌套数据结构?
How to validate a complex nested data structure with Pydantic?
我有如下复杂的嵌套数据结构:
{ 0: { 0: {'S': 'str1', 'T': 4, 'V': 0x3ff},
1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},
1: { 0: {'S': 'str3', 'T': 8, 'V': 0x1ff},
1: {'S': 'str4', 'T': 7, 'V': 0x0ff}},
......
}
它基本上是一个二维字典。最里面的字典跟在 {Str: str, str:int, str:int} 之后,而它的外部字典总是以整数作为索引的键。
Pydantic 有没有办法验证数据类型和数据结构?我的意思是如果有人用一个字符串作为外部字典的键更改数据,代码应该提示错误。或者,如果有人通过将 'V' 值放入字符串来调整内部字典,检查员需要对此进行投诉。
我是 Pydantic 的新手,发现它总是需要一个 str 类型的字段来存储任何数据...有什么想法吗?
您可以将 Dict
用作 custom root 类型,将 int
用作键类型(使用嵌套字典)。像这样:
from pydantic import BaseModel, StrictInt
from typing import Union, Literal, Dict
sample = {0: {0: {'S': 'str1', 'T': 4, 'V': 0x3ff},
1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},
1: {0: {'S': 'str3', 'T': 8, 'V': 0x1ff},
1: {'S': 'str4', 'T': 7, 'V': 0x0ff}}
}
# innermost model
class Data(BaseModel):
S: str
T: int
V: int
class Model(BaseModel):
__root__: Dict[int, Dict[int, Data]]
print(Model.parse_obj(sample))
我有如下复杂的嵌套数据结构:
{ 0: { 0: {'S': 'str1', 'T': 4, 'V': 0x3ff},
1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},
1: { 0: {'S': 'str3', 'T': 8, 'V': 0x1ff},
1: {'S': 'str4', 'T': 7, 'V': 0x0ff}},
......
}
它基本上是一个二维字典。最里面的字典跟在 {Str: str, str:int, str:int} 之后,而它的外部字典总是以整数作为索引的键。
Pydantic 有没有办法验证数据类型和数据结构?我的意思是如果有人用一个字符串作为外部字典的键更改数据,代码应该提示错误。或者,如果有人通过将 'V' 值放入字符串来调整内部字典,检查员需要对此进行投诉。
我是 Pydantic 的新手,发现它总是需要一个 str 类型的字段来存储任何数据...有什么想法吗?
您可以将 Dict
用作 custom root 类型,将 int
用作键类型(使用嵌套字典)。像这样:
from pydantic import BaseModel, StrictInt
from typing import Union, Literal, Dict
sample = {0: {0: {'S': 'str1', 'T': 4, 'V': 0x3ff},
1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},
1: {0: {'S': 'str3', 'T': 8, 'V': 0x1ff},
1: {'S': 'str4', 'T': 7, 'V': 0x0ff}}
}
# innermost model
class Data(BaseModel):
S: str
T: int
V: int
class Model(BaseModel):
__root__: Dict[int, Dict[int, Data]]
print(Model.parse_obj(sample))