TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

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

Резултати

Пронајдени 4 слични објави

Пребарај: #gamelaunch

当前筛选 #gamelaunch清除筛选
SingSing Announcement

@singsingchannel · Post #1130 · 24.12.2024 г., 01:25

🌟Mystic Garden is Officially Open!🌟 🎉 The wait is over—step into the magic now! 🔸AURA Launchpool Stakers: Your AURA rewards are ready! 🔸Beta Testers: Enjoy 2x AURA on your deposits and beta test reward as a special thank-you! 🔸Everyone: It’s time to explore, grow, and thrive in Mystic Garden! Let the adventure begin! 🌱✨ Play Now: https://t.me/mystic_garden_bot/app #MysticGarden#GameLaunch#AURARewards

SingSing Announcement

@singsingchannel · Post #1125 · 22.12.2024 г., 02:05

🎄Christmas is Coming... and so is Mystic Garden!🌟 This holiday season, unwrap the magic with the official launch of Mystic Garden on Dec 24! 🌱✨ Get ready to plant, harvest, and earn as the garden blooms with festive cheer. 🎁 Don’t miss it! #MysticGarden#GameLaunch#PlayToEarn#Web3Gaming

SingSing Announcement

@singsingchannel · Post #814 · 21.09.2024 г., 05:07

🚀 The long-awaited SingSing Tycoon Game is about to launch! 🚀 ⏰Save the schedule:14:00 UTC Today - Sep 21⏰ In just a few hours, you’ll officially step into the world of SingSing Tycoon! Get ready to build your own karaoke chain, upgrade booths, expand your shop, and grow your ultimate entertainment empire! 🎤💰 Exciting adventures await. Be prepared—this is going to be epic! 💥 #SingSingTycoon#GameLaunch#KaraokeEmpire#PlayToEarn#SingSing Announcement | Chat | X (Twitter) | Website | Game

SingSing Announcement

@singsingchannel · Post #816 · 21.09.2024 г., 16:57

🚀SingSing Tycoon Game is Officially LIVE!🚀 The wait is over, SingSing Tycoon Game is Live Now 👉https://t.me/SingSing_TG_bot/app?startapp=_ktvgame Build your empire, compete with friends, and rise to the top! 💼🏆 Note: Lucky Box Owners and Kara Box Owners can now unbox in the Tycoon Game! 🎁✨ Don’t miss out—start your journey today! 🎮 #SingSingTycoon#GameLaunch#PlayNow#BuildYourEmpire 🎤Announcement | Chat | X (Twitter) | Website | Game