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

Резултати

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

Пребарај: #privatesale

当前筛选 #privatesale清除筛选

🎙 SEASIDE CLUB announcing Seed Sale phase on December 🔥🔥🔥 📌 Seaside Club is an international holding company that comprises different business endeavors around the globe that has developed an innovative investment mechanism for retail and corporate investors. 📌 The core of the mechanism relies on the blockchain technology via a unique smart contract system, Seaside Coin and proof-of-ownership NFTs. 📌 Company deals with real estate, ore mining, agricultural production, motion picture industry, retail apparel and with a rage of digital projects including their own NFT marketplace and Metaverse. 💎 Seaside Coin 💎 The core of the Seaside Ecosystem! Unique coin that is backed by the real world businesses that are digitized via a special smart contract structure! 💎 Seaside Business Ecosystem 💎 A unique investment system that allows you to earn fixed 30% yearly returns on your total value locked in staking! Convenient, profitable and safe from volatility investment system that welcomes anyone! 💎 Own Branded TV Series 💎 In order to boost the global brand recognition Seaside Club is launching its own branded TV series "Crypto Hunters" on a major streaming and TV broadcasting platforms! Token information - Token name: $SEASIDE - Seed Phase: $0,15 - Private sale: $0,3$ - Total Supply: 2,000,000,000 ⏰ Seed Phase planed for December Learn more: - Opportunities: https://77d40765.flowpaper.com/SeasideClubOpportunitiesmatis/ - Tokenomics: https://77d40765.flowpaper.com/SeasideCoinTokenomicsMatis/ - Telegram: https://t.me/+O-ydB2I2CIBjYzhi #SEASIDE#Privatesale#NFTs

ABOUT RAGS TO RICHIE by Alec Monopoly Alec Monopoly is one of the most influential artists of Pop Culture. With a unique universe, he has shown his work on several occasions for Art Basel Miami and has collaborated with worldwide known brands such as Hermès, Jacob&Co, Louis Vuitton or TAG Heuer. Surrounded by NFT experts and Web3 creators, Alec quickly became aware of the importance of what’s been created today in the NFT space. 💰ONLY 2 DAYS LEFT BEFORE MINT! 💰 🗓 DATE REMINDER 🗓 🎩 MINT DATE: July 24th 2022, 2PM EST (6PM UTC) 💰 PRIVATE SALE: Open to Whitelist & Raffle winners at 2PM EST (6PM UTC) 💸 PUBLIC SALE: Open to everyone at 3PM EST (7PM UTC) 👉 More info: https://twitter.com/ragstorichienft/status/1550491484306247682?s=20&t=gzN4NwfON9CLTjI95VhKdQ #NFTs#alec#Privatesale