本文整理汇总了Python中pydantic.root_validator方法的典型用法代码示例。如果您正苦于以下问题:Python pydantic.root_validator方法的具体用法?Python pydantic.root_validator怎么用?Python pydantic.root_validator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pydantic
的用法示例。
在下文中一共展示了pydantic.root_validator方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_root_validator
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import root_validator [as 别名]
def test_root_validator():
validator_value = None
class TestCls:
x = 1
y = 2
class Model(BaseModel):
x: int
y: int
z: int
@root_validator(pre=True)
def change_input_data(cls, value):
nonlocal validator_value
validator_value = value
return {**value, 'z': value['x'] + value['y']}
class Config:
orm_mode = True
model = Model.from_orm(TestCls())
assert model.dict() == {'x': 1, 'y': 2, 'z': 3}
assert isinstance(validator_value, GetterDict)
assert validator_value == {'x': 1, 'y': 2}
示例2: test_value_validation
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import root_validator [as 别名]
def test_value_validation():
T = TypeVar('T')
class Response(GenericModel, Generic[T]):
data: T
@validator('data', each_item=True)
def validate_value_nonzero(cls, v):
if v == 0:
raise ValueError('value is zero')
return v
@root_validator()
def validate_sum(cls, values):
if sum(values.get('data', {}).values()) > 5:
raise ValueError('sum too large')
return values
assert Response[Dict[int, int]](data={1: '4'}).dict() == {'data': {1: 4}}
with pytest.raises(ValidationError) as exc_info:
Response[Dict[int, int]](data={1: 'a'})
assert exc_info.value.errors() == [
{'loc': ('data', 1), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
]
with pytest.raises(ValidationError) as exc_info:
Response[Dict[int, int]](data={1: 0})
assert exc_info.value.errors() == [{'loc': ('data', 1), 'msg': 'value is zero', 'type': 'value_error'}]
with pytest.raises(ValidationError) as exc_info:
Response[Dict[int, int]](data={1: 3, 2: 6})
assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'sum too large', 'type': 'value_error'}]
示例3: test_root_validator
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import root_validator [as 别名]
def test_root_validator():
root_val_values = []
@dataclass
class MyDataclass:
a: int
b: str
@validator('b')
def repeat_b(cls, v):
return v * 2
@root_validator
def root_validator(cls, values):
root_val_values.append(values)
if 'snap' in values.get('b', ''):
raise ValueError('foobar')
return dict(values, b='changed')
assert asdict(MyDataclass(a='123', b='bar')) == {'a': 123, 'b': 'changed'}
with pytest.raises(ValidationError) as exc_info:
MyDataclass(a=1, b='snap dragon')
assert root_val_values == [{'a': 123, 'b': 'barbar'}, {'a': 1, 'b': 'snap dragonsnap dragon'}]
assert exc_info.value.errors() == [{'loc': ('__root__',), 'msg': 'foobar', 'type': 'value_error'}]