1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] automatically add fields_validators based on hint type with pydantic

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024 às 09:02.

  1. Stack

    Stack Membro Participativo

    I'd like to define once for all fields_validators function in a BaseModel class, and inherit this class in my model, and the validators should apply to the updated class attributes.

    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



    I tried to use model_validate but then I lost the alias parsing

    Continue reading...

Compartilhe esta Página