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

Резултати

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

Пребарај: #defiecosystem

当前筛选 #defiecosystem清除筛选
TON Crypto News

@toncoin_rap · Post #107 · 04.09.2024 г., 17:19

🎧⤴ TON's Open League Season 6: Airdrops, DeFi Boosts & NFT Wars - Ready for September 12! The Open League Season 6 on The Open Network (TON) launches on September 12, shifting focus from competition to collaboration. Users can earn airdrops through Normie and Degen rewards by participating in DeFi, apps, and NFTs. Projects across the ecosystem also benefit from extra incentives, helping TON grow towards 500 million wallets and $1 billion in total value locked (TVL). Verse 1: Season 6, we ready, TON’s on the rise, Normie or Degen, you pick your prize. Airdrops droppin’, apps gettin’ hot, Buildin’ the ecosystem, ready or not. Chorus: 500 mil wallets, TVL through the sky, Open League’s here, reachin’ so high. DeFi, NFTs, stackin’ the gains, We all in this mission, breakin' the chains. Verse 2: DeFi pools deep, vaults full of gold, Projects in the League, their stories unfold. Top three teams, they get the crown, While communities rise, never backin' down. Chorus: 500 mil wallets, TVL through the sky, Open League’s here, reachin’ so high. DeFi, NFTs, stackin’ the gains, We all in this mission, breakin' the chains. Bridge: Mint that badge, Normie or Degen flow, Support the ecosystem, let the numbers grow. TON's the future, crypto on your phone, Together we rise, blockchain’s new throne. Verse 3: NFTs battle, ads on Telegram hit, DeFi League strong, vaults never quit. From apps to protocols, we bring the heat, Season 6 just started, victory's sweet! Chorus: 500 mil wallets, TVL through the sky, Open League’s here, reachin’ so high. DeFi, NFTs, stackin’ the gains, We all in this mission, breakin' the chains. #OpenLeague #DeFiEcosystem #TON 🎧@toncoin_rap