Использование 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
⚠️ ATTENTION ATTENTION! ⚠️
Gamety's very first X Podcast is here! 😮
We've been talking about #Gamety for some time. But some of you may still be wondering: "What is Gamety?" 😃
Set a reminder on your calendar!
Time: May 22, 2024, at 3 PM CET.
Venue: X Space
It's time to find out about us! 📈
Tweet 🔗:
https://x.com/gametyio/status/1792968517047988521
🖇 Important Links:
Website | X | Chat | Discord | Announcement | Youtube
For those of you who love engaging with Gamety's social media channels, we have a token of appreciation for you!
Join our Post-To-Airdrop program for a chance to win big from our massive 5,000,000 $GTY token pool! 💰
To participate:
1️⃣ Repost our announcement with #Gamety; @gametyio; and $GTY
2️⃣ Follow @gametyio
3️⃣ Promote for max engagement
More reach = Higher rank on @keani_gg Leaderboard!
Read more: https://keani.gg/gamety
Tweet 🔗:
https://x.com/gametyio/status/1789481845626667017?s=46
🖇 Important Links:
Website | X | Chat | Discord | Announcement | Youtube
👊Punch-to-Earn Airdrop👊
🏅Airdrop Prize Pool: 8,000,000 $GTY
Link: t.me/GametyApp_bot
Calling all gamers!
Who loves to punch someone in the face and earn some money from it?.👊💥
Inspired by the success story of @thenotcoin, Gamety brings tap gaming to the next level!
Invite friends to #Gamety's Telegram, rack up points & climb the leaderboard NOW! 🏆
🔗Tweet:
https://x.com/gametyio/status/1788666261288763550?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Bitcoin halving has been finally took place, cutting mining rewards to 3.125 BTC .
The new era of Bitcoin is starting, and #Gamety is here to ride the wave!
🔗 Tweet:
https://x.com/gametyio/status/1781498935594622998?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
🎉 We're thrilled to announce our partnership with MetaMuffin!🚀
As KOLs in the Web3 space, they'll be helping us spread the word about #Gamety's revolutionary gaming platform on Runes Protocol
Join us on this exciting journey together! 🕹✨
🔗 Tweet:
https://x.com/gametyio/status/1781371957512171916?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Innovation is at the heart of #Gamety’s P2E model.
Explore our cutting-edge game mechanics that redefine entertainment. 🕹️
Be our early members by joining our community now!
🔗 Tweet:
https://x.com/gametyio/status/1780368302159901131?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Learning meets leisure at #Gamety.
We're discussing educational content in Gamety’s socials to enrich our gaming ecosystem. 📚
What Web3 concept would you like to learn with us? 👀
Join our community to find out more!
🔗 Tweet:
https://x.com/gametyio/status/1779933725146640751?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
The #Gamety marketplace is where gaming meets commerce.
Trade in-game assets with ease and security on our platform. 🛍️
Let’s get your way to the top!
🔗 Tweet:
https://x.com/gametyio/status/1779575482679525580?s=46
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
🌙 Eid Mubarak to all celebrating around the world!
May this special day bring peace, happiness, and prosperity to everyone.
From #Gamety, with love 💕
🔗 Tweet:
https://x.com/gametyio/status/1778046881060503747
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
Tokens that do more!
Find out how $GTY fuels the #Gamety ecosystem, powering rewards, and in-game purchases.
Join our community to learn more!
🔗 Tweet:
https://twitter.com/gametyio/status/1777453037226991772?t=y7r0-4TMHMOkDvjPyXEolg&s=19
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
At #Gamety, every pixel is crafted with the player in mind. 😎
Want to be involved more as early members?
Our user-centric approach will be setting new standards in gaming experience! 🔲
Join our community now! 🚀
🔗 Tweet:
https://x.com/gametyio/status/1777063704519180769
🖇 Important Links:
Website | X | Chat | Announcement | Youtube
It is our pleasure to announce the DCI Capital as one of our investors in the Private Round! 🚀
Together, we can develop #Gamety as the revolutionary gaming platform for Bitcoin ecosystem! 🔲
🔗Twitter
https://x.com/gametyio/status/1775574940139581593?s=20
🖇Important Links:
Website | X | Chat | Announcement | Youtube