我想在 BaseModel 类中为所有 fields_validators 函数定义一次,并在我的模型中继承此类,并且验证器应应用于更新的类属性。
MWE
def to_int(v: Union[str, int]) -> int:
if isinstance(v, str):
if v.startswith("0x"):
return int(v, 16)
return int(v)
return v
def to_bytes(v: Union[str, bytes, list[int]]) -> bytes:
if isinstance(v, bytes):
return v
elif isinstance(v, str):
if v.startswith("0x"):
return bytes.fromhex(v[2:])
return v.encode()
else:
return bytes(v)
class BaseModelCamelCase(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
alias_generator=AliasGenerator(
validation_alias=lambda name: AliasChoices(to_camel(name), name)
),
)
# FIXME: should apply to int type from get_type_hints only
@field_validator("*", mode="before")
def to_int(cls, v: Union[str, int]) -> int:
return to_int(v)
# FIXME: should apply to bytes type from get_type_hints only
@field_validator("*", mode="before")
def to_bytes(cls, v: Union[str, bytes, list[int]]) -> bytes:
return to_bytes(v)
class BaseTransactionModel(BaseModelCamelCase):
nonce: int
gas: int = Field(validation_alias=AliasChoices("gasLimit", "gas_limit", "gas"))
to: Optional[bytes]
value: int
data: bytes
r: int = 0
s: int = 0
我尝试使用
model_validate
,但后来我丢失了别名解析
要根据 Pydantic 中的类型提示自动添加字段验证器,您可以使用 Typing_extensions 中的注释类型以及 Pydantic 的验证器函数。这允许您将验证逻辑直接绑定到类型,使您的代码更加模块化和可重用。
以下是如何实现此目标的示例:
from typing import Any, List
from typing_extensions import Annotated
from pydantic import BaseModel, ValidationError
from pydantic.functional_validators import AfterValidator
# Define a validator function
def check_positive(value: int) -> int:
if value <= 0:
raise ValueError(f'{value} is not a positive number')
return value
# Create an annotated type with the validator
PositiveInt = Annotated[int, AfterValidator(check_positive)]
# Use the annotated type in a Pydantic model
class MyModel(BaseModel):
positive_number: PositiveInt
# Example usage
try:
model = MyModel(positive_number=10)
print(model)
except ValidationError as e:
print(e)
try:
model = MyModel(positive_number=-5)
except ValidationError as e:
print(e)
说明: 验证器功能:check_positive 确保该值是正整数。 带注释的类型:PositiveInt 使用带注释的方式将 int 类型与 check_positive 验证器结合起来。 Pydantic 模型:MyModel 使用 PositiveInt 作为 Positive_number 字段,自动应用验证器。 好处: 模块化:验证器与类型绑定,使它们可以在不同的模型中重用。 清晰度:验证逻辑与模型定义分离,提高可读性。