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

Пребарај: #dst

当前筛选 #dst清除筛选
Airdrop Strikers™

@airdropstrikers · Post #266 · 29.04.2022 г., 15:17

📣📣📣DoctorS Token Airdrop $50,000 begins now: The biggest airdrop campaign of DoctorS Token $DST, we are Doctor Strange and Avengers lover community. It’s where we not only get huge earning but also sharing with many people. Let’s join and make us bigger! The DoctorS Token airdrop: 🎁 Reward: 100,000,000 $DST when you win the airdrop whitelist. 👨‍👧‍👦 Participants: Everyone 📌Registration: April 29th - May 3rd, 2022 💵Distribution: May 3rd - May 16th, 2022 🚀🚀 Click here to join: @DoctorSTokenAirdropBot More about us: 🌏Website: https://drstrangefan.io 🐦Twitter: https://twitter.com/DoctorSToken 📣Channel: @drstrangeann #DST#DSTToken#DoctorSToken#DoctorStrangeToken

🚀🚀The intelligent investors💯💯

@the_intelligent_investors · Post #421 · 05.05.2022 г., 10:43

⚡️⚡️⚡️Don't miss your chance!!! It's time to you to buy at dip price before SUPER BIG NEWS coming $DST is an only biggest community for whom love and follow Doctor Strange and Avengers team to create a meaningful and grow up decentralized-platform project together 💵💵 We're available on #coinmarketcap and live on #pancakeswap with smart contract: 0xa128a6216a8e8def817a31a06290f8055d6add2f Tax is 8-12% for Buy/Sell Find more about us: 🌏Website: https://drstrangefan.io 🐦Twitter: https://twitter.com/DoctorSToken 📣Channel: @drstrangeann 🗣 Group: https://t.me/drstrangeio #Doctorstoken#DSTtoken#DoctorStrangetoken#DoctorS #Doctorstrange#DST#DoctorStrangeInTheMultiverseOfMadness