@verse · Post #108 · 20.07.2024 г., 12:58
Cycling alone Past Andrew Wyeth fields – No lid on the world! #haiku by MR
Hashtags
TGINSIGHT SIMILAR POSTS
Изворен канал @pythonotes · Post #397 · 12 ное.
Использование Pydantic сегодня стало нормой, и это правильно. Но иногда на ревью вижу, что используют его не всегда корректно. Например, метод BaseModel.model_dump() по умолчанию не преобразует стандартные типы, такие как datetime, UUID или Decimal, в простой сериализуемый для JSON вид. Тогда пишут кастмоный сериализатор для этих типов чтобы функция json.dump() не падала с ошибкой. import uuid from datetime import datetime from decimal import Decimal from uuid import UUID from pydantic import BaseModel class MyModel(BaseModel): id: UUID date: datetime value: Decimal obj = MyModel( id=uuid.uuid4(), date=datetime.now(), value='1.23' ) print(obj.model_dump()) # не подходит для json.dump # { # 'id': UUID('4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1'), # 'date': datetime.datetime(2025, 12, 12, 12, 12, 12, 111111), # 'value': Decimal('1.23') # } # добавляем свой кастомный сериализатор json.dumps(obj.model_dump(), cls=MySerializer) # { # 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1', # 'date': '2025-12-12T12:12:12.111111', # 'value': '1.23' # } В данном случае класс MySerializer обрабатывает datetime, UUID и Decimal. Например так: class MySerializer(json.JSONEncoder): def default(self, o): if isinstance(o, Decimal): return str(o) elif isinstance(o, datetime): return o.isoformat() elif isinstance(o, UUID): return str(o) return super().default(o) Специально для тех, кто всё еще так делает - в этом нет необходимости! Pydantic может это сделать сам, просто нужно добавить параметр mode="json". json.dumps(obj.model_dump(mode="json")) # { # 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1', # 'date': '2012-12-12T12:12:12.111111', # 'value': '1.23' # } #pydantic#libs
Пребарај: #haiku
@verse · Post #108 · 20.07.2024 г., 12:58
Cycling alone Past Andrew Wyeth fields – No lid on the world! #haiku by MR
Hashtags
@PensivePost · Post #5246 · 31.05.2021 г., 07:56
Relationship. On a lonely night, Two strangers bumped into eachother. And a relationship bloomed. #review#haiku
@QuietWorld · Post #6840 · 31.10.2019 г., 23:30
🔖Haiku 🌸“To sleep on our thoughts, Is better than to lose sleep over rash actions” #haiku#life#wisdom @quietworld🍃
@QuietWorld · Post #6766 · 22.10.2019 г., 13:01
🔖Haiku 🌸“When cherry blossoms scatter, no regrets.” .·. even when the cherry blossoms live for only a short period of time, they fall to their death with no regrets – because they offered beauty and loveliness around them. #haiku#life#kindness @quietworld🍃
@PensivePost · Post #5276 · 05.06.2021 г., 14:33
Mind had no more muse The poet in me, died and rot And my haiku cried. #review#haiku#nandini
@PensivePost · Post #5713 · 06.05.2022 г., 13:01
#review#iam#haiku Is this the demise of the unique journey?? If yes!!! Then what else is there in our stores?? Sounds meaningless!!!
@PensivePost · Post #5309 · 18.06.2021 г., 11:16
Haiku Sunshine after rain, Droplets on the spider web Glisten on and off. #review#haiku#Florence
@PensivePost · Post #5300 · 16.06.2021 г., 06:16
Haiku The storm raged outside Frightening the little blue birds And rain fell sideways. #haiku#review#Florence
@PensivePost · Post #5296 · 15.06.2021 г., 07:09
Haiku Look at the prim rose Rain-soaked, wind-kissed and enticed Emanating joy! #haiku#review#Florence
@PensivePost · Post #5275 · 05.06.2021 г., 13:52
Haiku Flowers in garden Basking in the petrichor Sway in balmy wind. #review#haiku#Florence
@PensivePost · Post #5247 · 31.05.2021 г., 17:15
Haiku Dark grey clouds gathered, A drop of rain on my nose Eruption of joy! #review#haiku#Florence
@PensivePost · Post #5236 · 29.05.2021 г., 13:33
HaikuHaiku A blooming red rose With raindrops like pearls Blushes like a bride. #review#haiku#Florence