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

Пребарај: #ogcommunity

当前筛选 #ogcommunity清除筛选
MoonPlay

@moonplay_official · Post #40 · 24.06.2024 г., 18:59

New Partnership Announcement: MoonPlay x OGCommunity!🚀 Hey Space Cadets! Kick-starting this week with the announcement of our partnership with👾OGCommunity - a powerhouse in the gaming industry with over 2 million members. They have something for everyone: communication with like-minded people, learning something new, earning money, investing, influencing the development of the industry, developing and launching projects in gaming, taking part in eSports tournaments, and playing the most exciting games. Together, we’re set to elevate your gaming experience to cosmic heights! 🔝 What This PartnershipMeans for You: 👥Enhanced Community: Benefit from the expertise and influence of one of the most impactful communities in gaming. 💸New Opportunities: Discover unique ways to earn, invest, and play, brought to you by the combined efforts of MoonPlay and OGCommunity. ✅Industry Influence: Be part of a movement that shapes the future of gaming, supported by a robust ecosystem of projects and initiatives. Together with OGCommunity, we’re bringing more excitement, innovation, and opportunities to your space adventures. Stay tuned for more updates 👀 as we embark on this stellar journey together! Stellar adventures start here:@moon_land_bot🚀 JOIN OGCOMMUNITY: ✉Channel ❌Twitter 🤖Discord *⃣Linktr.ee🐝Blog🐝OGC App #ToTheMoon#OGCommunity#MoonPlay#partnership#ecosystem#blockchain#gamefi#web3#wenlisting#airdropsoon#communityfirst#taptap#clicker#game

MoonPlay

@moonplay_official · Post #67 · 16.07.2024 г., 17:33

New Mission Pack Alert 👀 OGCommunity, known for building the most influential community and ecosystem in the gaming industry, brings you a fresh pack of missions! Connect with over 2 million members 👥, gain new knowledge, and take part in epic gaming experiences. 👉 Head right to Missions tab and complete special tasks curated by OGCommunity to earn rewards. Don't miss out on this opportunity. Together, we’ll conquer the cosmos and build a thriving lunar colony! 🤩 👉Start your To The Moon adventure now!👈 Website | Telegram Chat | X | Discord | Medium #ToTheMoon#MoonPlay#OGCommunity#ecosystem#blockchain#gamefi#web3#wenlisting#squad#mission#communityfirst#taptap#clicker#game