本文整理匯總了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'}]