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

Резултати

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

Пребарај: #airdropalert

当前筛选 #airdropalert清除筛选
Airdrop Presents 🗽

@airdrop_presents · Post #2900 · 10.05.2024 г., 11:14

🎁 Exciting New Research for Our Community! ✍️ 🔥 Get Ready for an Exclusive Airdrop Campaign in partnership with Binance Web3 Wallet! 🌐 We're giving away a whopping 1M $ZKL tokens! 💰 ↪️Tasks are now LIVE: ↪️ Deposit to Nova ↪️ Deposit ETH to LayerBank ↪️ Swap on iZiSwap (minimum 5 $USDT) ↪️ Supply tokens on Aqua Don't miss this incredible opportunity! Join now to claim your share of the rewards! 💫🔥#Crypto#Airdrop#Blockchain ➡️Click here to participate: https://www.binance.com/en/activity/mission/zklink-nova-airdrop🚀 🌟 Hurry! This giveaway is valued at a staggering 3.5 million dollars! 🤑 Big news: Potential Binance listing on the horizon! ✔️🐰 🔶 OTC Price: 1-3💸 Check it out here: Link🐋#ZKL#AirdropAlert

Airdrop Gold : Crypto Airdrop

@airdropgoldchannel · Post #157247 · 22.07.2024 г., 09:39

🚀 Don't Miss Out on Blum Points! 🚀 Hey there! 👋 Have you heard about Blum? It's the hottest airdrop around, and rumor has it that it might even replace $NOT! 🔥 Blum points are super hard to get, but guess what? By joining our exclusive Blum SQUAD, you can easily rack up more Blum points! 🎉✨ Don't let this opportunity slip away – join us now and be part of the excitement! 🌟 👇👇👇 CLICK HERE TO JOIN CLICK HERE TO JOIN CLICK HERE TO JOIN #BlumTribe#AirdropAlert#CryptoFOMO#BLUM $BLUM

SingSing Announcement

@singsingchannel · Post #904 · 16.10.2024 г., 14:10

🚨 Leaderboard Update: Tycoon Master Showdown 🚨 The leaderboard is heating up as players race for those top spots! 💰 Who's ready to claim their share of $KARA and those sweet NFT + TON bonuses? 🎁 There’s still time to make your move, so don’t let up! 🏆 👀 Oh, and did we mention a big airdrop is coming soon? Keep those eyes peeled—something massive is on the horizon! 🌟 #TycoonMaster#AirdropAlert#KARA#NFT#SingSingShowdown 🎤Announcement | Chat | X (Twitter) | Website | Game