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

Пребарај: #regionaltensions

当前筛选 #regionaltensions清除筛选
Crypto M - Crypto News

@CryptoM · Post #65138 · 11.04.2026 г., 11:05

🚀 Iran's Key Concerns Highlighted Amid Regional Tensions Iran's national television has reported on the country's critical issues amid ongoing regional tensions. According to Odaily, Iran's red lines include the strategic Strait of Hormuz, the payment of war reparations, the unfreezing of Iranian assets, and a ceasefire across the region. #Iran#RegionalTensions#StraitOfHormuz#WarReparations#FrozenAssets#Ceasefire

Crypto M - Crypto News

@CryptoM · Post #64843 · 10.04.2026 г., 03:34

🚀 Iranian Officials Remain in Tehran Amid Regional Tensions Iranian Foreign Minister Araghchi and Speaker Qalibaf have not left Iran, according to Odaily. Both officials are currently in Tehran, actively fulfilling their national duties amid evolving regional circumstances. A source stated that reports of an Iranian negotiation team arriving in Islamabad for talks with the U.S. are entirely false. The source emphasized that negotiations will remain stalled as long as the U.S. does not fulfill its ceasefire commitments in Lebanon and the Zionist regime continues its attacks. Previously, The Wall Street Journal claimed that an Iranian delegation arrived in Islamabad on Thursday night. #Iran#Tehran#RegionalTensions#Diplomacy#MiddleEast#USIranRelations#Lebanon#ZionistRegime