pydantic_core
SchemaValidator ¶
SchemaValidator(
schema: CoreSchema, config: CoreConfig | None = None
)
SchemaValidator
是 pydantic-core
的 Rust 验证逻辑的 Python 包装器,内部它拥有一个 CombinedValidator
,它可能反过来拥有更多构成完整模式验证器的 CombinedValidator
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
schema
|
CoreSchema
|
用于验证的 |
required |
config
|
CoreConfig | None
|
可选的 |
None
|
validate_python ¶
validate_python(
input: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None,
allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False,
by_alias: bool | None = None,
by_name: bool | None = None
) -> Any
根据模式验证 Python 对象并返回验证后的对象。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Any
|
要验证的 Python 对象。 |
required |
strict
|
bool | None
|
是否在严格模式下验证对象。如果为 |
None
|
from_attributes
|
bool | None
|
是否通过提取属性来验证作为模型输入的对象。如果为 |
None
|
context
|
Any | None
|
用于验证的上下文,这将作为 |
None
|
self_instance
|
Any | None
|
从验证中设置属性的模型实例,这在从模型的 |
None
|
allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
是否允许部分验证;如果为 |
False
|
by_alias
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
Raises
类型 | 描述 |
---|---|
ValidationError
|
如果验证失败。 |
Exception
|
如果发生内部错误,可能会引发其他错误类型。 |
Returns
类型 | 描述 |
---|---|
Any
|
验证后的对象。 |
isinstance_python ¶
isinstance_python(
input: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None
) -> bool
类似于 validate_python()
,但返回一个布尔值。
参数与 validate_python()
匹配。此方法不会引发 ValidationError
,但会引发内部错误。
Returns
类型 | 描述 |
---|---|
bool
|
如果验证成功,则为 |
validate_json ¶
validate_json(
input: str | bytes | bytearray,
*,
strict: bool | None = None,
context: Any | None = None,
self_instance: Any | None = None,
allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False,
by_alias: bool | None = None,
by_name: bool | None = None
) -> Any
直接根据模式验证 JSON 数据并返回验证后的 Python 对象。
此方法应比 validate_python(json.loads(json_data))
快得多,因为它避免了创建中间 Python 对象的需要
它还处理构造正确的 Python 类型,即使在严格模式下,validate_python(json.loads(json_data))
也会验证失败。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
str | bytes | bytearray
|
要验证的 JSON 数据。 |
required |
strict
|
bool | None
|
是否在严格模式下验证对象。如果为 |
None
|
context
|
Any | None
|
用于验证的上下文,这将作为 |
None
|
self_instance
|
Any | None
|
从验证中设置属性的模型实例。 |
None
|
allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
是否允许部分验证;如果为 |
False
|
by_alias
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
Raises
类型 | 描述 |
---|---|
ValidationError
|
如果验证失败或 JSON 数据无效。 |
Exception
|
如果发生内部错误,可能会引发其他错误类型。 |
Returns
类型 | 描述 |
---|---|
Any
|
验证后的 Python 对象。 |
validate_strings ¶
validate_strings(
input: _StringInput,
*,
strict: bool | None = None,
context: Any | None = None,
allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False,
by_alias: bool | None = None,
by_name: bool | None = None
) -> Any
根据模式验证字符串并返回验证后的 Python 对象。
这类似于 validate_json
,但适用于输入将是字符串但不是 JSON 数据的场景,例如 URL 片段、查询参数等。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
_StringInput
|
输入为字符串,如果 |
required |
strict
|
bool | None
|
是否在严格模式下验证对象。如果为 |
None
|
context
|
Any | None
|
用于验证的上下文,这将作为 |
None
|
allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
是否允许部分验证;如果为 |
False
|
by_alias
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
Raises
类型 | 描述 |
---|---|
ValidationError
|
如果验证失败或 JSON 数据无效。 |
Exception
|
如果发生内部错误,可能会引发其他错误类型。 |
Returns
类型 | 描述 |
---|---|
Any
|
验证后的 Python 对象。 |
validate_assignment ¶
validate_assignment(
obj: Any,
field_name: str,
field_value: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: Any | None = None,
by_alias: bool | None = None,
by_name: bool | None = None
) -> (
dict[str, Any]
| tuple[dict[str, Any], dict[str, Any] | None, set[str]]
)
验证对模型上字段的赋值。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
obj
|
Any
|
要赋值的模型实例。 |
required |
field_name
|
str
|
要验证赋值的字段名称。 |
required |
field_value
|
Any
|
要赋值给字段的值。 |
required |
strict
|
bool | None
|
是否在严格模式下验证对象。如果为 |
None
|
from_attributes
|
bool | None
|
是否通过提取属性来验证作为模型输入的对象。如果为 |
None
|
context
|
Any | None
|
用于验证的上下文,这将作为 |
None
|
by_alias
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在根据提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
Raises
类型 | 描述 |
---|---|
ValidationError
|
如果验证失败。 |
Exception
|
如果发生内部错误,可能会引发其他错误类型。 |
Returns
类型 | 描述 |
---|---|
dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]
|
模型字典或 |
get_default_value ¶
获取模式的默认值,包括运行默认值验证。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
strict
|
bool | None
|
是否在严格模式下验证默认值。如果为 |
None
|
context
|
Any
|
用于验证的上下文,这将作为 |
None
|
Raises
类型 | 描述 |
---|---|
ValidationError
|
如果验证失败。 |
Exception
|
如果发生内部错误,可能会引发其他错误类型。 |
Returns
类型 | 描述 |
---|---|
Some | None
|
如果模式没有默认值,则为 |
SchemaSerializer ¶
SchemaSerializer(
schema: CoreSchema, config: CoreConfig | None = None
)
SchemaSerializer
是 pydantic-core
的 Rust 序列化逻辑的 Python 包装器,内部它拥有一个 CombinedSerializer
,它可能反过来拥有更多构成完整模式序列化器的 CombinedSerializer
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
schema
|
CoreSchema
|
用于序列化的 |
required |
config
|
CoreConfig | None
|
可选的 |
None
|
to_python ¶
to_python(
value: Any,
*,
mode: str | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: (
bool | Literal["none", "warn", "error"]
) = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> Any
将 Python 对象序列化/编组为 Python 对象,包括转换和过滤数据。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
value
|
Any
|
要序列化的 Python 对象。 |
required |
mode
|
str | None
|
要使用的序列化模式,可以是 |
None
|
include
|
_IncEx | None
|
要包含的字段集合,如果为 |
None
|
exclude
|
_IncEx | None
|
要排除的字段集合,如果为 |
None
|
by_alias
|
bool | None
|
use_alias |
None
|
exclude_unset
|
bool
|
是否排除未设置的字段,例如未包含在 |
False
|
exclude_defaults
|
bool
|
是否排除与其默认值相等的字段。 |
False
|
exclude_none
|
bool
|
是否排除值为 |
False
|
round_trip
|
bool
|
是否启用序列化和验证往返支持。 |
False
|
warnings
|
bool | Literal['none', 'warn', 'error']
|
如何处理无效字段。False/"none" 忽略它们,True/"warn" 记录错误,"error" 引发 |
True
|
fallback
|
Callable[[Any], Any] | None
|
遇到未知值时要调用的函数,如果为 |
None
|
serialize_as_any
|
bool
|
是否使用鸭子类型序列化行为序列化字段。 |
False
|
context
|
Any | None
|
context |
None
|
Raises
类型 | 描述 |
---|---|
PydanticSerializationError
|
如果序列化失败且未提供 |
Returns
类型 | 描述 |
---|---|
Any
|
序列化后的 Python 对象。 |
to_json ¶
to_json(
value: Any,
*,
indent: int | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: (
bool | Literal["none", "warn", "error"]
) = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> bytes
将 Python 对象序列化为 JSON,包括转换和过滤数据。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
value
|
Any
|
要序列化的 Python 对象。 |
required |
indent
|
int | None
|
如果为 |
None
|
include
|
_IncEx | None
|
要包含的字段集合,如果为 |
None
|
exclude
|
_IncEx | None
|
要排除的字段集合,如果为 |
None
|
by_alias
|
bool | None
|
use_alias |
None
|
exclude_unset
|
bool
|
是否排除未设置的字段,例如未包含在 |
False
|
exclude_defaults
|
bool
|
是否排除与其默认值相等的字段。 |
False
|
exclude_none
|
bool
|
是否排除值为 |
False
|
round_trip
|
bool
|
是否启用序列化和验证往返支持。 |
False
|
warnings
|
bool | Literal['none', 'warn', 'error']
|
如何处理无效字段。False/"none" 忽略它们,True/"warn" 记录错误,"error" 引发 |
True
|
fallback
|
Callable[[Any], Any] | None
|
遇到未知值时要调用的函数,如果为 |
None
|
serialize_as_any
|
bool
|
是否使用鸭子类型序列化行为序列化字段。 |
False
|
context
|
Any | None
|
context |
None
|
Raises
类型 | 描述 |
---|---|
PydanticSerializationError
|
如果序列化失败且未提供 |
Returns
类型 | 描述 |
---|---|
bytes
|
JSON 字节。 |
ValidationError ¶
基类: ValueError
ValidationError
是 pydantic-core
在验证失败时引发的异常,它包含一个错误列表,详细说明了验证失败的原因。
from_exception_data classmethod
¶
from_exception_data(
title: str,
line_errors: list[InitErrorDetails],
input_type: Literal["python", "json"] = "python",
hide_input: bool = False,
) -> Self
Validation Error 的 Python 构造函数。
用于构造验证错误的 API 将来可能会更改,因此使用静态方法而不是 __init__
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
title
|
str
|
title |
required |
line_errors
|
list[InitErrorDetails]
|
|
required |
input_type
|
Literal['python', 'json']
|
错误是针对 Python 对象还是 JSON。 |
'python'
|
hide_input
|
bool
|
是否在错误消息中隐藏输入值。 |
False
|
errors ¶
errors(
*,
include_url: bool = True,
include_context: bool = True,
include_input: bool = True
) -> list[ErrorDetails]
详细说明验证错误中的每个错误。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
include_url
|
bool
|
是否为每个错误包含指向错误文档的 URL。 |
True
|
include_context
|
bool
|
是否包含每个错误的上下文。 |
True
|
include_input
|
bool
|
是否包含每个错误的输入值。 |
True
|
Returns
类型 | 描述 |
---|---|
list[ErrorDetails]
|
验证错误中每个错误的 |
ErrorDetails ¶
InitErrorDetails ¶
SchemaError ¶
PydanticCustomError ¶
PydanticCustomError(
error_type: LiteralString,
message_template: LiteralString,
context: dict[str, Any] | None = None,
)
基类: ValueError
一个自定义异常,为 Pydantic 验证器提供灵活的错误处理。
当您希望在错误类型、消息和上下文方面具有灵活性时,可以在自定义验证器中引发此错误。
示例
from pydantic_core import PydanticCustomError
def custom_validator(v) -> None:
if v <= 10:
raise PydanticCustomError('custom_value_error', 'Value must be greater than {value}', {'value': 10, 'extra_context': 'extra_data'})
return v
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
error_type
|
LiteralString
|
错误类型。 |
required |
message_template
|
LiteralString
|
message_template |
required |
context
|
dict[str, Any] | None
|
要注入到消息模板中的数据。 |
None
|
PydanticKnownError ¶
基类: ValueError
一个辅助类,用于引发模仿 Pydantic 内置异常的异常,在上下文方面具有更大的灵活性。
与 PydanticCustomError
不同,error_type
参数必须是已知的 ErrorType
。
示例
from pydantic_core import PydanticKnownError
def custom_validator(v) -> None:
if v <= 10:
raise PydanticKnownError(error_type='greater_than', context={'gt': 10})
return v
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
error_type
|
ErrorType
|
错误类型。 |
required |
context
|
dict[str, Any] | None
|
要注入到消息模板中的数据。 |
None
|
PydanticOmit ¶
基类: Exception
一个异常,用于指示应从生成的结果中省略字段。
这可以跨越从 JSON Schema 中省略字段到从序列化结果中省略字段。 即将推出:对在自定义序列化器中使用 PydanticOmit 的更强大的支持仍在开发中。 目前,这主要用于 JSON Schema 生成过程。
示例
from typing import Callable
from pydantic_core import PydanticOmit
from pydantic import BaseModel
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
class MyGenerateJsonSchema(GenerateJsonSchema):
def handle_invalid_for_json_schema(self, schema, error_info) -> JsonSchemaValue:
raise PydanticOmit
class Predicate(BaseModel):
name: str = 'no-op'
func: Callable = lambda x: x
instance_example = Predicate()
validation_schema = instance_example.model_json_schema(schema_generator=MyGenerateJsonSchema, mode='validation')
print(validation_schema)
'''
{'properties': {'name': {'default': 'no-op', 'title': 'Name', 'type': 'string'}}, 'title': 'Predicate', 'type': 'object'}
'''
有关更深入的示例/说明,请参阅自定义 JSON schema 文档。
PydanticUseDefault ¶
基类: Exception
一个异常,用于指示标准验证失败或应跳过,并且应改用默认值。
可以在自定义验证函数中引发此警告,以重定向验证流程。
示例
from pydantic_core import PydanticUseDefault
from datetime import datetime
from pydantic import BaseModel, field_validator
class Event(BaseModel):
name: str = 'meeting'
time: datetime
@field_validator('name', mode='plain')
def name_must_be_present(cls, v) -> str:
if not v or not isinstance(v, str):
raise PydanticUseDefault()
return v
event1 = Event(name='party', time=datetime(2024, 1, 1, 12, 0, 0))
print(repr(event1))
# > Event(name='party', time=datetime.datetime(2024, 1, 1, 12, 0))
event2 = Event(time=datetime(2024, 1, 1, 12, 0, 0))
print(repr(event2))
# > Event(name='meeting', time=datetime.datetime(2024, 1, 1, 12, 0))
有关其他示例,请参阅 Pydantic 文档的验证部分 json 数据部分。
PydanticSerializationError ¶
PydanticSerializationError(message: str)
基类: ValueError
序列化期间发生问题时引发的错误。
在自定义序列化器中,此错误可用于指示序列化已失败。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
message
|
str
|
message |
required |
PydanticSerializationUnexpectedValue ¶
PydanticSerializationUnexpectedValue(message: str)
基类: ValueError
序列化期间遇到意外值时引发的错误。
此错误通常被捕获并强制转换为警告,因为 pydantic-core
通常会尽最大努力序列化值,这与急切引发错误的验证形成对比。
示例
from pydantic import BaseModel, field_serializer
from pydantic_core import PydanticSerializationUnexpectedValue
class BasicPoint(BaseModel):
x: int
y: int
@field_serializer('*')
def serialize(self, v):
if not isinstance(v, int):
raise PydanticSerializationUnexpectedValue(f'Expected type `int`, got {type(v)} with value {v}')
return v
point = BasicPoint(x=1, y=2)
# some sort of mutation
point.x = 'a'
print(point.model_dump())
'''
UserWarning: Pydantic serializer warnings:
PydanticSerializationUnexpectedValue(Expected type `int`, got <class 'str'> with value a)
return self.__pydantic_serializer__.to_python(
{'x': 'a', 'y': 2}
'''
这通常在 pydantic-core
内部使用,当在序列化期间遇到意外类型时,但用户也可以在自定义序列化器中使用它,如上所示。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
message
|
str
|
message |
required |
MultiHostUrl ¶
MultiHostUrl(url: str)
基类: SupportsAllComparisons
支持多主机的 URL 类型,如某些数据库用于 DSN,例如 https://foo.com,bar.com/path
。
内部 URL 逻辑使用最初由 Mozilla 开发的 url rust crate。
MultiHostHost ¶
ArgsKwargs ¶
用于存储函数调用的参数和关键字参数的构造。
此数据结构通常用于存储与函数关联的核心模式的信息(如参数模式中)。 此数据结构目前也用于对数据类进行某些验证。
示例
from pydantic.dataclasses import dataclass
from pydantic import model_validator
@dataclass
class Model:
a: int
b: int
@model_validator(mode="before")
@classmethod
def no_op_validator(cls, values):
print(values)
return values
Model(1, b=2)
#> ArgsKwargs((1,), {"b": 2})
Model(1, 2)
#> ArgsKwargs((1, 2), {})
Model(a=1, b=2)
#> ArgsKwargs((), {"a": 1, "b": 2})
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
args
|
tuple[Any, ...]
|
args |
required |
kwargs
|
dict[str, Any] | None
|
kwargs |
None
|
Some ¶
基类: Generic[_T]
类似于 Rust 的 Option::Some
类型,这会将一个值标识为存在,并提供一种访问它的方法。
通常在与 None
的联合中使用,以区分“某些可能为 None 的值”和无值。
TzInfo ¶
基类: tzinfo
pydantic-core
对抽象类 datetime.tzinfo
的实现。
tzname ¶
返回与 datetime
对象 dt 相对应的时区名称,以字符串形式返回。
更多信息,请参阅 tzinfo.tzname
。
utcoffset ¶
返回本地时间与 UTC 的偏移量,以 timedelta
对象表示,UTC 以东为正。如果本地时间位于 UTC 以西,则应为负数。
更多信息请参阅 tzinfo.utcoffset
。
dst ¶
返回夏令时 (DST) 调整量,以 timedelta
对象或 None
表示,如果 DST 信息未知。
更多信息请参阅 tzinfo.dst
。
fromutc ¶
调整与 datetime 对象 dt 关联的日期和时间数据,返回 self 的本地时间等效 datetime。
更多信息请参阅 tzinfo.fromutc
。
ErrorTypeInfo ¶
基类: TypedDict
提供关于错误的信息。
message_template_python instance-attribute
¶
message_template_python: str
字符串模板,用于在使用上下文渲染人类可读的错误消息,当输入是 Python 时。
message_template_json instance-attribute
¶
message_template_json: NotRequired[str]
字符串模板,用于在使用上下文渲染人类可读的错误消息,当输入是 JSON 数据时。
example_message_json instance-attribute
¶
example_message_json: NotRequired[str]
人类可读的错误消息示例,当输入是 JSON 数据时。
to_json ¶
to_json(
value: Any,
*,
indent: int | None = None,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal["iso8601", "float"] = "iso8601",
bytes_mode: Literal["utf8", "base64", "hex"] = "utf8",
inf_nan_mode: Literal[
"null", "constants", "strings"
] = "constants",
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> bytes
将 Python 对象序列化为 JSON,包括转换和过滤数据。
这实际上是 SchemaSerializer.to_json
的独立版本。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
value
|
Any
|
要序列化的 Python 对象。 |
required |
indent
|
int | None
|
如果为 |
None
|
include
|
_IncEx | None
|
要包含的字段集合,如果为 |
None
|
exclude
|
_IncEx | None
|
要排除的字段集合,如果为 |
None
|
by_alias
|
bool
|
use_alias |
True
|
exclude_none
|
bool
|
是否排除值为 |
False
|
round_trip
|
bool
|
是否启用序列化和验证往返支持。 |
False
|
timedelta_mode
|
Literal['iso8601', 'float']
|
如何序列化 |
'iso8601'
|
bytes_mode
|
Literal['utf8', 'base64', 'hex']
|
如何序列化 |
'utf8'
|
inf_nan_mode
|
Literal['null', 'constants', 'strings']
|
如何序列化 |
'constants'
|
serialize_unknown
|
bool
|
尝试序列化未知类型,将使用 |
False
|
fallback
|
Callable[[Any], Any] | None
|
遇到未知值时要调用的函数,如果为 |
None
|
serialize_as_any
|
bool
|
是否使用鸭子类型序列化行为序列化字段。 |
False
|
context
|
Any | None
|
context |
None
|
Raises
类型 | 描述 |
---|---|
PydanticSerializationError
|
如果序列化失败且未提供 |
Returns
类型 | 描述 |
---|---|
bytes
|
JSON 字节。 |
from_json ¶
from_json(
data: str | bytes | bytearray,
*,
allow_inf_nan: bool = True,
cache_strings: (
bool | Literal["all", "keys", "none"]
) = True,
allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False
) -> Any
将 JSON 数据反序列化为 Python 对象。
这实际上是更快版本的 json.loads()
,带有一些额外的功能。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
data
|
str | bytes | bytearray
|
要反序列化的 JSON 数据。 |
required |
allow_inf_nan
|
bool
|
是否允许 |
True
|
cache_strings
|
bool | Literal['all', 'keys', 'none']
|
是否缓存字符串以避免构建新的 Python 对象,这应该会对性能产生显著影响,同时略微增加内存使用量, |
True
|
allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
是否允许部分反序列化,如果为 |
False
|
Raises
类型 | 描述 |
---|---|
ValueError
|
如果反序列化失败。 |
Returns
类型 | 描述 |
---|---|
Any
|
反序列化的 Python 对象。 |
to_jsonable_python ¶
to_jsonable_python(
value: Any,
*,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal["iso8601", "float"] = "iso8601",
bytes_mode: Literal["utf8", "base64", "hex"] = "utf8",
inf_nan_mode: Literal[
"null", "constants", "strings"
] = "constants",
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: Any | None = None
) -> Any
序列化/编组 Python 对象为 JSON 可序列化的 Python 对象,包括转换和过滤数据。
这实际上是 SchemaSerializer.to_python(mode='json')
的独立版本。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
value
|
Any
|
要序列化的 Python 对象。 |
required |
include
|
_IncEx | None
|
要包含的字段集合,如果为 |
None
|
exclude
|
_IncEx | None
|
要排除的字段集合,如果为 |
None
|
by_alias
|
bool
|
use_alias |
True
|
exclude_none
|
bool
|
是否排除值为 |
False
|
round_trip
|
bool
|
是否启用序列化和验证往返支持。 |
False
|
timedelta_mode
|
Literal['iso8601', 'float']
|
如何序列化 |
'iso8601'
|
bytes_mode
|
Literal['utf8', 'base64', 'hex']
|
如何序列化 |
'utf8'
|
inf_nan_mode
|
Literal['null', 'constants', 'strings']
|
如何序列化 |
'constants'
|
serialize_unknown
|
bool
|
尝试序列化未知类型,将使用 |
False
|
fallback
|
Callable[[Any], Any] | None
|
遇到未知值时要调用的函数,如果为 |
None
|
serialize_as_any
|
bool
|
是否使用鸭子类型序列化行为序列化字段。 |
False
|
context
|
Any | None
|
context |
None
|
Raises
类型 | 描述 |
---|---|
PydanticSerializationError
|
如果序列化失败且未提供 |
Returns
类型 | 描述 |
---|---|
Any
|
序列化后的 Python 对象。 |