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

Резултати

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

Пребарај: #countdown

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

@singsingchannel · Post #962 · 04.11.2024 г., 14:20

🚀 Only one week left until our IDO launches! The excitement is building up as we get closer to the big day. Get ready to join us on this incredible journey! #IDO#Countdown#SingSing🎉 🎤Announcement | Chat | X (Twitter) | Website | Game

SingSing Announcement

@singsingchannel · Post #952 · 01.11.2024 г., 14:08

🚀 Let’s Countdown Together! 🚀 The big day is coming—SingSing’s IDO is set for November 11! 🎉 Get ready for an epic sale event and your chance to grab $SING! 🔥 Countdown with us on Website and SingSing Mini App! Mark your calendars, bring your best game, and let’s make this an unforgettable IDO together! ⏰ #SingSing#IDO#Countdown#GetReady 🎤Announcement | Chat | X (Twitter) | Website | Game

Oʻzbekiston Qilichbozlik Federatsiyasi

@fencinguzbekistan · Post #3966 · 22.05.2025 г., 05:49

⏳ Countdown is on! Only 26 days left until one of Asia’s biggest fencing showdowns! 🌏🤺 📍 Bali – Indonesia 📆 June 17–23, 2025 🏆 Senior Asian Fencing Championship Top athletes are getting ready for an electrifying competition! Stay tuned for full access 📸 and live highlights from the heart of the action 🎥🔥 #Fencing⚔️#Bali2025#AsianChampionship #FCA#FIE#SeniorAsianFencingChampionship2025 #Indonesia#FencingAsia#Countdown

VISION11

@vision11official · Post #1328 · 02.09.2023 г., 06:02

#Power-packed #battle on the pitch.🔥🔥 Are you ready for an India🇮🇳 vs. Pakistan showdown?💪😎 Make you #teams for #AsiaCup contest and win bumper #rewards.⏳️🏌‍♀️ Only on #Vision11, #download now. #india#cricket#asia#asiacup2023#battle#countdown#begin#cricketfans#reward#bonus#vision#vision11