Использование 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
#Web3Festival in Hong Kong wrapped up during a tough week for the crypto market, but builder momentum was high and the community remains active 🔥
Announcements such as TON Blockchain's TON wallet expanding into the U.S. and events hosted by Monad and BNB Chain indicate that the space is still moving forward.
For a recap on highlights from this past week, read the DWF Ventures team's summary here.
DWF Ventures continues to support teams building through every cycle. If you're working on something, get in touch: https://www.dwf-labs.com/ventures
During our week at #Web3Festival in Hong Kong, Eugene Ng, Founding Partner of DWF Labs, gave a talk on the mainstage about the newest trends and narratives in Web3 innovations.
He discussed the rise of Bitcoin ecosystems, the institutionalisation of crypto as an asset class; memecoins, AI and more. 💥
Missed his speech? Check out the livestream recap.
#Web3Festival was a successful week, and we especially enjoyed our side event, DWF Labs Haus, on Sunday night. 🌙
It was an evening of delicious cocktails and canapés, fantastic company, and insightful conversations. Thank you to everyone who came!
During #Web3Festival Hong Kong, our team was able to share insights about innovations that are heating up in the crypto space. 🔥
Yesterday, Fiona Ma, Senior Associate at DWF Ventures, gave a speech about decoding the Ethereum restaking landscape, delving into the evolution from staking to restaking.
Restaking is one of the verticals DWF Ventures is highly interested in - if you're a project innovating in multiple sectors, feel free to reach out to their team on X!
Our team had an amazing time at #Web3Festival in Hong Kong!
It was our second year sponsoring Web3 Festival, and this year was even bigger and better than the last. 🔥
It was a pleasure to meet our friends and partners in person at our booth. Thank you to everyone who came by!
About last night... 👀
That's a wrap on our event, DWF Labs Haus, during #Web3Festival Hong Kong. 🔥
Meeting industry leaders, founders, and innovators in person is always a pleasure as we continue to work from a diverse network of cities and countries worldwide.
Thank you to everyone who attended, it was great to meet you all!
Setting up for our DWF Labs Haus event during #Web3Festival, which kicks off at 6 PM. 👀
We're in full swing gearing up to host an unforgettable evening filled with incredible networking opportunities and delicious cocktails and canapés.
Looking forward to meeting everyone soon!
The teaser for Hong Kong #Web3Festival 2024 just dropped!
We're excited to be Title Sponsors of this event ✨
Get ready for this spectacular gathering of #Web3 set for April 6-9 🔥
Get February offer: https://lu.ma/hkweb3festival2024
🌎TONCA$H Travel Cashback is ON!
Planning to hit Hong Kong #Web3Festival or Dubai #Token2049? Why not earn cashback in $BTC, $TON, or $USDT when booking your trip?
Hot Deals:
⚡️ 10% cashback on flights🛬
⚡️ 20% cashback on hotels📍
How to Claim?
✅ Book your trip via TONCash App
✅ Receive your cashback in $BTC, $TON, or $USDT directly in your wallet! T&Cs apply
💵Get Your Place Now!🏝
#TONCash#Travel#Web3#HongKongWeb3Festival#DubaiToken2049#Cashback