Автоматически добавлять поля_валидаторы на основе типа подсказки с помощью pydanticPython

Программы на Python
Anonymous
Автоматически добавлять поля_валидаторы на основе типа подсказки с помощью pydantic

Сообщение Anonymous »

Я хотел бы определить один раз для всех функцию полей_валидаторов в классе BaseModel и унаследовать этот класс в моей модели, а валидаторы должны применяться к обновленным атрибутам класса.
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, но потом потерял анализ псевдонима


Подробнее здесь: https://stackoverflow.com/questions/790 ... h-pydantic

Вернуться в «Python»