功能验证器
此模块包含用于验证的相关类和函数。
ModelAfterValidatorWithoutInfo module-attribute
¶
ModelAfterValidatorWithoutInfo = Callable[
[_ModelType], _ModelType
]
一个 @model_validator
装饰的函数签名。当 mode='after'
且函数没有 info 参数时使用。
ModelAfterValidator module-attribute
¶
ModelAfterValidator = Callable[
[_ModelType, ValidationInfo], _ModelType
]
一个 @model_validator
装饰的函数签名。当 mode='after'
时使用。
AfterValidator dataclass
¶
AfterValidator(
func: (
NoInfoValidatorFunction | WithInfoValidatorFunction
),
)
使用文档
一个元数据类,指示验证应在内部验证逻辑之后应用。
属性
名称 | 类型 | 描述 |
---|---|---|
func |
NoInfoValidatorFunction | WithInfoValidatorFunction
|
验证器函数。 |
示例
from typing import Annotated
from pydantic import AfterValidator, BaseModel, ValidationError
MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a=1).a)
#> 2
try:
Model(a='a')
except ValidationError as e:
print(e.json(indent=2))
'''
[
{
"type": "int_parsing",
"loc": [
"a"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "a",
"url": "https://errors.pydantic.dev/2/v/int_parsing"
}
]
'''
BeforeValidator dataclass
¶
BeforeValidator(
func: (
NoInfoValidatorFunction | WithInfoValidatorFunction
),
json_schema_input_type: Any = PydanticUndefined,
)
使用文档
一个元数据类,指示验证应在内部验证逻辑之前应用。
属性
名称 | 类型 | 描述 |
---|---|---|
func |
NoInfoValidatorFunction | WithInfoValidatorFunction
|
验证器函数。 |
json_schema_input_type |
Any
|
函数的输入类型。这仅用于生成适当的 JSON Schema(在验证模式下)。 |
示例
from typing import Annotated
from pydantic import BaseModel, BeforeValidator
MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a=1).a)
#> 2
try:
Model(a='a')
except TypeError as e:
print(e)
#> can only concatenate str (not "int") to str
PlainValidator dataclass
¶
PlainValidator(
func: (
NoInfoValidatorFunction | WithInfoValidatorFunction
),
json_schema_input_type: Any = Any,
)
使用文档
一个元数据类,指示验证应代替内部验证逻辑应用。
注意
在 v2.9 之前,PlainValidator
并非始终与 mode='validation'
的 JSON Schema 生成兼容。您现在可以使用 json_schema_input_type
参数来指定函数在 mode='validation'
(默认)下用于 JSON schema 的输入类型。有关更多详细信息,请参见下面的示例。
属性
名称 | 类型 | 描述 |
---|---|---|
func |
NoInfoValidatorFunction | WithInfoValidatorFunction
|
验证器函数。 |
json_schema_input_type |
Any
|
函数的输入类型。这仅用于生成适当的 JSON Schema(在验证模式下)。如果未提供,则默认为 |
示例
from typing import Annotated, Union
from pydantic import BaseModel, PlainValidator
MyInt = Annotated[
int,
PlainValidator(
lambda v: int(v) + 1, json_schema_input_type=Union[str, int] # (1)!
),
]
class Model(BaseModel):
a: MyInt
print(Model(a='1').a)
#> 2
print(Model(a=1).a)
#> 2
- 在此示例中,我们将
json_schema_input_type
指定为Union[str, int]
,这向 JSON schema 生成器指示,在验证模式下,字段a
的输入类型可以是str
或int
。
WrapValidator dataclass
¶
WrapValidator(
func: (
NoInfoWrapValidatorFunction
| WithInfoWrapValidatorFunction
),
json_schema_input_type: Any = PydanticUndefined,
)
使用文档
一个元数据类,指示验证应在内部验证逻辑周围应用。
属性
名称 | 类型 | 描述 |
---|---|---|
func |
NoInfoWrapValidatorFunction | WithInfoWrapValidatorFunction
|
验证器函数。 |
json_schema_input_type |
Any
|
函数的输入类型。这仅用于生成适当的 JSON Schema(在验证模式下)。 |
from datetime import datetime
from typing import Annotated
from pydantic import BaseModel, ValidationError, WrapValidator
def validate_timestamp(v, handler):
if v == 'now':
# we don't want to bother with further validation, just return the new value
return datetime.now()
try:
return handler(v)
except ValidationError:
# validation failed, in this case we want to return a default value
return datetime(2000, 1, 1)
MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
class Model(BaseModel):
a: MyTimestamp
print(Model(a='now').a)
#> 2032-01-02 03:04:05.000006
print(Model(a='invalid').a)
#> 2000-01-01 00:00:00
ModelWrapValidatorHandler ¶
Bases: ValidatorFunctionWrapHandler
, Protocol[_ModelTypeCo]
@model_validator
装饰的函数处理器参数类型。当 mode='wrap'
时使用。
ModelWrapValidatorWithoutInfo ¶
FreeModelBeforeValidatorWithoutInfo ¶
ModelBeforeValidatorWithoutInfo ¶
InstanceOf dataclass
¶
InstanceOf()
用于注释给定类的实例类型的泛型类型。
示例
from pydantic import BaseModel, InstanceOf
class Foo:
...
class Bar(BaseModel):
foo: InstanceOf[Foo]
Bar(foo=Foo())
try:
Bar(foo=42)
except ValidationError as e:
print(e)
"""
[
│ {
│ │ 'type': 'is_instance_of',
│ │ 'loc': ('foo',),
│ │ 'msg': 'Input should be an instance of Foo',
│ │ 'input': 42,
│ │ 'ctx': {'class': 'Foo'},
│ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of'
│ }
]
"""
SkipValidation dataclass
¶
SkipValidation()
如果将其用作注释(例如,通过 x: Annotated[int, SkipValidation]
),则会跳过验证。您也可以使用 SkipValidation[int]
作为 Annotated[int, SkipValidation]
的简写。
如果您想使用类型注释进行文档/IDE/类型检查,并且知道跳过一个或多个字段的验证是安全的,这将非常有用。
由于这会将验证模式转换为 any_schema
,因此后续应用的注释转换可能不会产生预期的效果。因此,当使用此注释时,它通常应是应用于类型的最终注释。
field_validator ¶
field_validator(
field: str,
/,
*fields: str,
mode: Literal["wrap"],
check_fields: bool | None = ...,
json_schema_input_type: Any = ...,
) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]
field_validator(
field: str,
/,
*fields: str,
mode: FieldValidatorModes = "after",
check_fields: bool | None = None,
json_schema_input_type: Any = PydanticUndefined,
) -> Callable[[Any], Any]
使用文档
装饰类上的方法,指示它们应用于验证字段。
使用示例
from typing import Any
from pydantic import (
BaseModel,
ValidationError,
field_validator,
)
class Model(BaseModel):
a: str
@field_validator('a')
@classmethod
def ensure_foobar(cls, v: Any):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
print(repr(Model(a='this is foobar good')))
#> Model(a='this is foobar good')
try:
Model(a='snap')
except ValidationError as exc_info:
print(exc_info)
'''
1 validation error for Model
a
Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str]
'''
有关更深入的示例,请参见 字段验证器。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
field
|
str
|
应在其上调用 |
required |
*fields
|
str
|
应在其上调用 |
()
|
mode
|
FieldValidatorModes
|
指定是在验证之前还是之后验证字段。 |
'after'
|
check_fields
|
bool | None
|
是否检查字段是否实际存在于模型上。 |
None
|
json_schema_input_type
|
Any
|
函数的输入类型。这仅用于生成适当的 JSON Schema(在验证模式下),并且仅当 |
PydanticUndefined
|
返回
类型 | 描述 |
---|---|
Callable[[Any], Any]
|
一个装饰器,可用于装饰要用作 field_validator 的函数。 |
引发
类型 | 描述 |
---|---|
PydanticUserError
|
|
源代码在 pydantic/functional_validators.py
中
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
|
model_validator ¶
model_validator(*, mode: Literal["wrap"]) -> Callable[
[_AnyModelWrapValidator[_ModelType]],
PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
使用文档
装饰用于验证目的的模型方法。
使用示例
from typing_extensions import Self
from pydantic import BaseModel, ValidationError, model_validator
class Square(BaseModel):
width: float
height: float
@model_validator(mode='after')
def verify_square(self) -> Self:
if self.width != self.height:
raise ValueError('width and height do not match')
return self
s = Square(width=1, height=1)
print(repr(s))
#> Square(width=1.0, height=1.0)
try:
Square(width=1, height=2)
except ValidationError as e:
print(e)
'''
1 validation error for Square
Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict]
'''
有关更深入的示例,请参见 模型验证器。
参数
名称 | 类型 | 描述 | 默认 |
---|---|---|---|
mode
|
Literal['wrap', 'before', 'after']
|
一个必需的字符串字面量,用于指定验证模式。它可以是以下之一:'wrap'、'before' 或 'after'。 |
required |
返回
类型 | 描述 |
---|---|
Any
|
一个装饰器,可用于装饰要用作模型验证器的函数。 |
源代码在 pydantic/functional_validators.py
中
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 |
|