mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
f55515820a
* renaming .json -> .model_dump_json * renaming .dict -> .model_dump * renaming .__fields__ -> .model_fields * renaming .schema -> .model_json_schema * renaming .construct -> .model_construct * renaming .parse_obj -> .model_validate * make linters happy * add changes md-file Co-authored-by: Samuel Colvin <s@muelcolvin.com>
44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
from typing import Generic, TypeVar, Optional, List
|
|
|
|
from pydantic import BaseModel, validator, ValidationError
|
|
from pydantic.generics import GenericModel
|
|
|
|
DataT = TypeVar('DataT')
|
|
|
|
|
|
class Error(BaseModel):
|
|
code: int
|
|
message: str
|
|
|
|
|
|
class DataModel(BaseModel):
|
|
numbers: List[int]
|
|
people: List[str]
|
|
|
|
|
|
class Response(GenericModel, Generic[DataT]):
|
|
data: Optional[DataT]
|
|
error: Optional[Error]
|
|
|
|
@validator('error', always=True)
|
|
def check_consistency(cls, v, values):
|
|
if v is not None and values['data'] is not None:
|
|
raise ValueError('must not provide both data and error')
|
|
if v is None and values.get('data') is None:
|
|
raise ValueError('must provide data or error')
|
|
return v
|
|
|
|
|
|
data = DataModel(numbers=[1, 2, 3], people=[])
|
|
error = Error(code=404, message='Not found')
|
|
|
|
print(Response[int](data=1))
|
|
print(Response[str](data='value'))
|
|
print(Response[str](data='value').model_dump())
|
|
print(Response[DataModel](data=data).model_dump())
|
|
print(Response[DataModel](error=error).model_dump())
|
|
try:
|
|
Response[int](data='value')
|
|
except ValidationError as e:
|
|
print(e)
|