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 слични објави

Пребарај: #lastchance

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

@singsingchannel · Post #704 · 16.07.2024 г., 10:53

🚨 Only 1 day left until the Top Club Referral event ends! ⏳ Don't miss your chance to invite more members to your club and win amazing rewards from SingSing. Act fast and make your club the best 👉link🌟 🥇Top 1: 10,000 RUBY shared among all Club Members + 0.01 ETH for Club Owner 🥈Top 2-4: 5,000 RUBY shared among all Club Members + 0.007 ETH for Club Owner 🥉Top 5-7: 3,000 RUBY shared among all Club Members + 0.003 ETH or Club Owner 🏅Top 8-10: 2,000 RUBY shared among all Club Members Total prize pool: 20,000 RUBY and 0.02 ETH! 💎✨ Note: Top clubs will be determined by the number of members joining through each club's referral link. Read more and open Treasure at: X Post #SingSing#TopClubReferral#LastChance

SLEX NEWS

@slex_io · Post #159 · 16.02.2024 г., 10:20

🚀 Great Start of SLEX Launchpad!🎉 ⚡️The first day of SLEX Launchpad sales was a huge success with over 37,78% of allocations sold out! Whitelist participants, you have a last chance to be part of this exclusive event, but hurry up as allocation actively decreases with high users demand📈 🗓️The sale ends tomorrow, February 17th. Don't miss the last chance to take exclusive advantages of SLEX Launchpad. #SLEXLaunchpad#LastChance#CryptoSale Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

SLEX NEWS

@slex_io · Post #129 · 23.11.2023 г., 09:22

📣 Final Call for SLEX Rewards! 🌟 🎁Dear, SLEXians, our rewards form is closing soon! Don’t miss your last chance to claim tokens SLEX. Fill out the Zealy contest form by the 24th of November 2023🎉 🏃‍♂️💨 Hurry, time is ticking, and this is your final reminder. Complete the process to ensure you don’t miss out! 👉bit.ly/3s3Ey46👈 #SLEXRewards#LastChance#CryptoCommunity#SLEXPrizes Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter

SingSing Announcement

@singsingchannel · Post #821 · 22.09.2024 г., 12:56

🚨 RUBY Mining Feature Closing at 13:00 UTC on Sep 23! 🚨 Today’s your last chance to mine and claim RUBY! ⏳⛏💎 RUBY is still essential for several game features and boosting your in-game earnings, so don’t miss out! 🎮💰 Get those final rewards before the feature shuts down! #SingSing#RUBYMining#LastChance#GameBoost#SingSingTycoon 🎤Announcement | Chat | X (Twitter) | Website | Game