Guest User

Untitled

a guest
Mar 28th, 2023
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. import json
  2. import time
  3. import orjson
  4. from pydantic import BaseModel, conlist
  5.  
  6.  
  7. class InnerModel(BaseModel):
  8.     id: int
  9.     name: str
  10.  
  11.  
  12. class FooModel(BaseModel):
  13.     x: int
  14.     y: dict[str, str] = {}
  15.     inner_model: conlist(InnerModel, max_items=10, min_items=8)
  16.  
  17.  
  18. class FooModelList(BaseModel):
  19.     data: list[FooModel]
  20.  
  21.  
  22. def load_bytes():
  23.     with open('file.json', 'rb') as file:
  24.         return file.read()
  25.  
  26.  
  27. def load_data_pydantic():
  28.     with open('file.json') as file:
  29.         raw_data = json.load(file)
  30.  
  31.     return FooModelList(**raw_data)
  32.  
  33.  
  34. def test_encode_pydantic():
  35.     foo_list = load_data_pydantic()
  36.     start_time = time.monotonic()
  37.     foo_list.json(encoder=orjson.dumps)
  38.     print('Pydantic + orjson, Encode: ', time.monotonic() - start_time)
  39.  
  40.  
  41. def test_decode_pydantic():
  42.     raw_data = load_bytes()
  43.     start_time = time.monotonic()
  44.     FooModelList(**orjson.loads(raw_data))
  45.     print('Pydantic + orjson, Decode: ', time.monotonic() - start_time)
  46.  
  47.  
  48. test_encode_pydantic()
  49. test_decode_pydantic()
  50.  
Advertisement
Add Comment
Please, Sign In to add comment