本文整理匯總了Python中pydantic.validator方法的典型用法代碼示例。如果您正苦於以下問題:Python pydantic.validator方法的具體用法?Python pydantic.validator怎麽用?Python pydantic.validator使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pydantic
的用法示例。
在下文中一共展示了pydantic.validator方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_validate_pre
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_validate_pre():
@dataclass
class MyDataclass:
a: List[int]
@validator('a', pre=True)
def check_a1(cls, v):
v.append('123')
return v
@validator('a')
def check_a2(cls, v):
v.append(456)
return v
assert MyDataclass(a=[1, 2]).a == [1, 2, 123, 456]
示例2: test_inheritance_replace
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_inheritance_replace():
@dataclass
class Parent:
a: int
@validator('a')
def add_to_a(cls, v):
return v + 1
@dataclass
class Child(Parent):
@validator('a')
def add_to_a(cls, v):
return v + 5
assert Child(a=0).a == 5
示例3: test_validate_assignment_value_change
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_validate_assignment_value_change():
class Config:
validate_assignment = True
@pydantic.dataclasses.dataclass(config=Config, frozen=False)
class MyDataclass:
a: int
@validator('a')
def double_a(cls, v):
return v * 2
d = MyDataclass(2)
assert d.a == 4
d.a = 3
assert d.a == 6
示例4: test_error_on_optional
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_error_on_optional():
class Foobar(BaseModel):
foo: Optional[str] = None
@validator('foo', always=True, pre=True)
def check_foo(cls, v):
raise ValueError('custom error')
with pytest.raises(ValidationError) as exc_info:
Foobar(foo='x')
assert exc_info.value.errors() == [{'loc': ('foo',), 'msg': 'custom error', 'type': 'value_error'}]
assert repr(exc_info.value.raw_errors[0]) == "ErrorWrapper(exc=ValueError('custom error'), loc=('foo',))"
with pytest.raises(ValidationError) as exc_info:
Foobar(foo=None)
assert exc_info.value.errors() == [{'loc': ('foo',), 'msg': 'custom error', 'type': 'value_error'}]
示例5: test_assert_raises_validation_error
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_assert_raises_validation_error():
test_name = test_assert_raises_validation_error.__name__
class Model(BaseModel):
a: str
@validator('a')
def check_a(cls, v):
assert v == 'a', 'invalid a'
return v
Model(a='a')
expected_errors = [{'loc': ('a',), 'msg': 'invalid a', 'type': 'assertion_error'}]
try:
Model(a='snap')
except ValidationError as exc:
actual_errors = exc.errors()
if actual_errors != expected_errors:
raise RuntimeError(f'{test_name}:\nActual errors: {actual_errors}\nExpected errors: {expected_errors}')
else:
raise RuntimeError(f'{test_name}: ValidationError was not raised')
示例6: test_root_validator
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import 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'}]
示例7: reload_config
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def reload_config():
global config
class FullConfig(BaseModel):
DataRoot: str = '/root/coolq/data/image'
LogRoot: str = '/var/log/umr'
CommandPrefix: str = '!!'
Extensions: Optional[List[str]]
BotAdmin: Optional[Dict[str, List[Union[int, str]]]]
LogLevel: Optional[Dict[str, LogLevel]]
ForwardList: ForwardList
Driver: Optional[Dict[str, construct_union(driver_config, BaseDriverConfig)]]
ExtensionConfig: Optional[Dict[str, construct_union(extension_config, BaseExtensionConfig)]]
@validator('Extensions', pre=True, always=True)
def generate_empty_list_if_none(cls, v):
return v or []
@validator('Driver', pre=True, always=True)
def generate_empty_dict_if_none(cls, v):
return v or {}
@validator('ExtensionConfig', pre=True, always=True)
def generate_empty_dict_if_none2(cls, v):
return v or {}
@validator('BotAdmin', pre=True, always=True)
def generate_empty_dict_if_none3(cls, v):
return v or {}
@validator('LogLevel', pre=True, always=True)
def generate_empty_dict_if_none4(cls, v):
return v or {}
config = FullConfig(**yaml.load(open(f'{home}/.umr/config.yaml'), yaml.FullLoader))
示例8: check_names_not_empty
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def check_names_not_empty(cls, v):
assert v != '', 'Empty strings are not allowed.'
return v
# This will NOT raise a ValidationError because the validator was not called
示例9: test_value_validation
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import 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'}]
示例10: test_simple
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_simple():
@dataclass
class MyDataclass:
a: str
@validator('a')
def change_a(cls, v):
return v + ' changed'
assert MyDataclass(a='this is foobar good').a == 'this is foobar good changed'
示例11: test_classmethod
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_classmethod():
@dataclass
class MyDataclass:
a: str
@validator('a')
def check_a(cls, v):
assert cls is MyDataclass and is_dataclass(MyDataclass)
return v
m = MyDataclass(a='this is foobar good')
assert m.a == 'this is foobar good'
m.check_a('x')
示例12: test_validate_parent
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_validate_parent():
@dataclass
class Parent:
a: str
@validator('a')
def change_a(cls, v):
return v + ' changed'
@dataclass
class Child(Parent):
pass
assert Parent(a='this is foobar good').a == 'this is foobar good changed'
assert Child(a='this is foobar good').a == 'this is foobar good changed'
示例13: test_inheritance_validators
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_inheritance_validators():
class BarModel(BaseModel):
@validator('a', check_fields=False)
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
model = create_model('FooModel', a='cake', __base__=BarModel)
assert model().a == 'cake'
assert model(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
model(a='something else')
示例14: test_inheritance_validators_always
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_inheritance_validators_always():
class BarModel(BaseModel):
@validator('a', check_fields=False, always=True)
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
model = create_model('FooModel', a='cake', __base__=BarModel)
with pytest.raises(ValidationError):
model()
assert model(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
model(a='something else')
示例15: test_inheritance_validators_all
# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import validator [as 別名]
def test_inheritance_validators_all():
class BarModel(BaseModel):
@validator('*')
def check_all(cls, v):
return v * 2
model = create_model('FooModel', a=(int, ...), b=(int, ...), __base__=BarModel)
assert model(a=2, b=6).dict() == {'a': 4, 'b': 12}