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

Резултати

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

Пребарај: #capital

当前筛选 #capital清除筛选
DWF Labs Broadcast

@DWFLabs · Post #244 · 09.03.2023 г., 00:00

We're excited to be able to support the mission of Tonstarter in bringing #builders, #community and #capital together to accelerate the growth of #TON ecosystem. Let's keep working towards building a future for TON together! ✨ Full announcement here. // About Tonstarter: ▫️Tonstarter is the first TON-native launchpad, enabling crypto projects to raise capital in a decentralized, safe, and user-friendly environment. Find out more here.

DWF Labs Broadcast

@DWFLabs · Post #251 · 15.03.2023 г., 00:00

Congratulations Tonstarter on closing a $1.5 million investment seed round! 🎉 We're proud to support your mission to unite #builders, #community, and #capital to accelerate the #growth of TON ecosystem ⚡ It's exciting to be building a bright future together 🫡 Full announcement here.

Venture Village Wall 🦄

@venturevillagewall · Post #4287 · 02.03.2025 г., 16:00

Trump Launches U.S. Crypto Reserve Initiative Former President Trump announces a U.S. Crypto Reserve to bolster the crypto industry, including assets like XRP, SOL, and ADA. The initiative aims to counteract previous administrations’ criticisms and position the U.S. as the global crypto capital. Investors react as $ADA surges 30% post-announcement. Read more here. #Crypto#ADA#XRP#SOL#Trump#US#DigitalAssets#Investment#Capital#Blockchain

Venture Village Wall 🦄

@venturevillagewall · Post #3493 · 19.12.2024 г., 13:58

Vibly Fundraising Highlights Vibly has successfully raised $734.92K in its latest funding round, which took place on December 19, 2024. For more information, visit their website: Vibly. #Vibly#Funding#Investment#Startup#Tech#Finance#Innovation#Business#FundingRound#Capital#Growth#Entrepreneurship#Market#Development#Strategy#VentureCapital #2024

Venture Village Wall 🦄

@venturevillagewall · Post #3397 · 18.12.2024 г., 12:10

Standard Wellness Secures $10M Funding Standard Wellness has successfully raised $10 million in funding as of December 17, 2024. The company is dedicated to enhancing quality of life by providing safe and easy access to cannabis. #Funding#Cannabis#Healthcare#QualityOfLife#Investment#StandardWellness#Capital#Access#Wellness#Health

ПретходнаСтраница 1 од 3Следна