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>
43 lines
838 B
Python
43 lines
838 B
Python
import pickle
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from pydantic import BaseModel, ValidationError
|
|
|
|
|
|
class User(BaseModel):
|
|
id: int
|
|
name = 'John Doe'
|
|
signup_ts: datetime = None
|
|
|
|
|
|
m = User.model_validate({'id': 123, 'name': 'James'})
|
|
print(m)
|
|
|
|
try:
|
|
User.model_validate(['not', 'a', 'dict'])
|
|
except ValidationError as e:
|
|
print(e)
|
|
|
|
# assumes json as no content type passed
|
|
m = User.parse_raw('{"id": 123, "name": "James"}')
|
|
print(m)
|
|
|
|
pickle_data = pickle.dumps({
|
|
'id': 123,
|
|
'name': 'James',
|
|
'signup_ts': datetime(2017, 7, 14)
|
|
})
|
|
m = User.parse_raw(
|
|
pickle_data, content_type='application/pickle', allow_pickle=True
|
|
)
|
|
print(m)
|
|
|
|
path = Path('data.json')
|
|
path.write_text('{"id": 123, "name": "James"}')
|
|
m = User.parse_file(path)
|
|
print(m)
|
|
# ignore-below
|
|
if path.exists():
|
|
path.unlink()
|