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

Резултати

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

Пребарај: #odaily

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

@CryptoM · Post #64935 · 10.04.2026 г., 10:55

🚀 Strategy's Stretch Nears Significant Bitcoin Acquisition Strategy's Stretch (STRC) is reportedly close to acquiring a substantial amount of Bitcoin this week. According to Odaily, the company is estimated to have raised enough funds to purchase 8,000 BTC. By the end of the week, STRC may hold a total of 10,000 BTC. #Strategy#Bitcoin#BTC#Acquisition#STRC#Odaily

Crypto M - Crypto News

@CryptoM · Post #64795 · 10.04.2026 г., 00:15

🚀 Kremlin Announces Easter Truce for April 2026 The Kremlin has announced a ceasefire to take place from April 11, 2026, at 16:00 until the end of April 12, 2026. According to Odaily, this truce is set to coincide with the Easter holiday. Further details about the ceasefire have not been disclosed. #Kremlin#EasterTruce#Ceasefire#April2026#Odaily#EasterHoliday

Crypto M - Crypto News

@CryptoM · Post #64518 · 09.04.2026 г., 05:44

🚀 Middle East Ceasefire Expected to Hold Despite Fragility Jefferies global economist Mohit Kumar has stated that despite the fragility of the Middle East ceasefire agreement, it is expected to hold. According to Odaily, Kumar noted that both parties have reached a point where they desire a ceasefire, as continued conflict would negatively impact both sides. Kumar highlighted that U.S. President Donald Trump is keen on reaching an agreement, as he lacks support from his core base for ongoing warfare. Meanwhile, the Iranian Revolutionary Guard faces challenges due to economic devastation, potentially paving the way for future uprisings. He concluded that given the interests of both parties, the unstable ceasefire is likely to persist. #MiddleEast#Ceasefire#MohitKumar#US#Iran#DonaldTrump#Conflict#RevolutionaryGuard#GlobalEconomics#PeaceAgreement#Odaily

Crypto M - Crypto News

@CryptoM · Post #65217 · 12.04.2026 г., 03:45

🚀 WLFI Co-Founder Addresses Misunderstandings on X Platform WLFI co-founder Zach Witkoff has responded to recent criticisms on the X platform regarding the WLFI project. According to Odaily, Witkoff clarified several points to address misconceptions. Firstly, he emphasized that WLFI should not be confused with the Trump meme coin, as they are entirely unrelated. He also stated that WLFI has no connection with 'fight fight fight' or CIC Digital Company. Witkoff highlighted that early investors purchased WLFI at prices of $0.015 and $0.05, with the current price standing at $0.08. He further explained that the project's primary product is not transaction fees but a stablecoin that generates returns through holding government bonds. This stablecoin ranks as the second-largest compliant stablecoin by trading volume and market capitalization, which he described as a significant achievement. Witkoff advised critics to conduct more thorough research before writing extensive posts on the matter. #WLFI#ZachWitkoff#XPlatform#TrumpMemeCoin#Stablecoin#GovernmentBonds#Investors#Misunderstandings#CICDigitalCompany#Cryptocurrency#Odaily#MarketCapitalization