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

Резултати

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

Пребарај: #referandearn

当前筛选 #referandearn清除筛选
MoonPlay

@moonplay_official · Post #34 · 20.06.2024 г., 15:38

Invite Your Friends To Join the Lunar Odyssey🧑‍🚀 Our mission to the moon is just getting started, and we need more brave souls like you! Invite your friends🔊 to join the adventure and help build our lunar colony. The more crew members we have, the stronger our efforts and the greater our discoveries. Every friend you bring on board not only boosts our mission but also unlocks rewards and opportunities for you: 💰one-time bonus; 👛% of space bucks mined by a friend as long as they play (even after the expedition you hire them for); 🤗crew members purchase (different members require different number of friends invited); each hired member will be earning you extra SB/hour. Remember that you need full crew to set off to the moon! Go to Crew tab -> Refer & Earn🔗, share your referral link, and let's make history together! P.S. Just in case you’d run out of friends to invite, there are specially trained bots🤖ready to step in. Nothing can stop you on the way to the moon! Stellar adventures start here:@moon_land_bot🚀 Website | Telegram Chat | X | Discord | Medium #ToTheMoon#MoonPlay#ecosystem#blockchain#gamefi#web3#wenlisting#airdropsoon#communityfirst#taptap#clicker#game#invitefriends#referralreward#referandearn

Bounty Hunters 💎

@trustedairdropsss · Post #374 · 10.12.2020 г., 11:56

Want to win big? Invite your friends to join 11Wickets & get rewarded! Download the app👉https://11wickets.sng.link/Dfcpe/ljeu . . . #11Wickets#IndiaOnTheGo#FantasyFootball#FantasySports#Football#ReferAndEarn#Refer#ReferYourFriends

Bounty Hunters 💎

@trustedairdropsss · Post #513 · 14.01.2021 г., 07:53

Want to win big? Invite your friends to join Rummy24 & get rewarded! (T&C apply). Download the app👉https://rummy24.sng.link/Averc/fcz2/lcft . . . #Rummy24#RummyApp#Rummy#RummyGame#IndianRummy#ReferAndEarn#ReferFriends#Invite#Earn#Rewards#Inviteyourfriends#EarnCash#Referafriend#EarnMoney#EarnMoneyOnline#Games#CardGames#DownloadTheApp