当前位置: 首页>>代码示例>>Python>>正文


Python pydantic.validator方法代码示例

本文整理汇总了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] 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:18,代码来源:test_validators_dataclass.py

示例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 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:18,代码来源:test_validators_dataclass.py

示例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 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:19,代码来源:test_dataclasses.py

示例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'}] 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:18,代码来源:test_errors.py

示例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') 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:24,代码来源:try_assert.py

示例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'}] 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:28,代码来源:test_validators_dataclass.py

示例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)) 
开发者ID:JQ-Networks,项目名称:UnifiedMessageRelay,代码行数:39,代码来源:UMRConfig.py

示例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 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:8,代码来源:validators_subclass_each_item.py

示例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'}] 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:34,代码来源:test_generics.py

示例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' 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:12,代码来源:test_validators_dataclass.py

示例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') 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:15,代码来源:test_validators_dataclass.py

示例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' 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:17,代码来源:test_validators_dataclass.py

示例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') 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:15,代码来源:test_create_model.py

示例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') 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:16,代码来源:test_create_model.py

示例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} 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:10,代码来源:test_create_model.py


注:本文中的pydantic.validator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。