Использование 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
👀 Well, would you look at that! 👆
Reached 9th TP on our #BABYUSDT trade! 🔥🔥🔥
Using a 5% entry you could've earned $305 with a $1000 deposit
ACCESS TO MANUAL TRADING for 70usdt/month
💪Rule the market with Propheta AI Signals: ultra-sharp alerts, full-on process automation, and a killer Cornix synergy — your fast track to max profits! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptomarket#tradingviewindicator#buycrypto
Now that's trading 👆🔥🔥🔥
#BABYUSDT has just reached 9th TP in the VIP HTL channel!!!
Trade took just 13 hours! 👍
$302 in profits with a 5% entry and a $1000 deposit!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 We know how to earn 3-4-5 digit amounts without any deposit, with zero risk! Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#cryptobot#crypto
Now that's trading 👆🔥🔥🔥
#BABYUSDT has just reached 9th TP in the VIP HTL channel!!!👍
With a 5% entry and a $1000 deposit, you could've earned $304!
ACCESS TO MANUAL TRADING for 70usdt/month
💸Turn time into cash with Propheta AI Signals: pinpoint entries and exits, AI-powered automation, and perfect Cornix compatibility — your automated win streak! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoin#buybtc#passiveincome
👀 Well, would you look at that! 👆
#BABYUSDT reached 9th TP in under 9 minutes!
Signal from our VIP HTL channel!
Easy $318 with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 OOooh yeah baby! And that's what we do every day! Every day milking those exchanges dry! Waiting for you: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoin#btc#cryptonews
Oops, we did it again 🤣
Reached 9th TP on our #BABYUSDT trade! 🔥🔥🔥
Using a 5% entry you could've earned $301 with a $1000 deposit
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Only in our community will you get several useful channels for the price of one sub!
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingindicator#btc#AItrading
👍 This is why we're here!
Reached 9th TP in 44 minutes on our #BABYUSDT trade! 🔥🔥🔥
Using a 5% entry you could've earned $314 with a $1000 deposit
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 We ain't only bragging about those profits, we're publishing the most transparent performance reports you can personally audit!
Come and see for yourself: @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#passiveincome#tradingview#crypto
👆 OMG! Would you look at that 👀
#BABYUSDT has just reached 9th TP in the VIP HTL channel!!!
Trade took just 12 hours! 👍
With a 5% entry and a $1000 deposit, you could've earned $302!
ACCESS TO MANUAL TRADING for 70usdt/month
🏆Flex your skills with Propheta AI Analyzer: smart AI analysis flips the market upside down, fast tweaks fit any style, and it’s your wingman for snagging top-tier trades! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#eth#tradingindicator#trading
👆 Propheta living up to its name yet again 🔮
#BABYUSDT has just reached 9th TP in the VIP HTL channel!!!👍
Using a 5% entry you could've earned $304 with a $1000 deposit
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
📊Dominate the market with Propheta AI Analyzer: AI uncovers hidden patterns with razor-sharp analysis, adapts on the fly with slick customization, and delivers next-level pair hunting — your edge for strategic supremacy! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingview#indicator#autotrading
👆 OMG! Would you look at that 👀
#BABYUSDT has just reached 9th TP in the VIP CLUB channel!!!
Trade took just 9 hours! 👍
ACCESS TO MANUAL TRADING for 70usdt/month
👉 Looking at those reports and can't believe what you're seing?
Go to our reports channel and audit us! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptotrading#signalchannel#eth
#BABYUSDT has just reached 9th TP in the VIP PRO channel!!!👍
With a 5% entry and a $1000 deposit, you could've earned $643!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Did you know that many traders use our performance reports to build their own trading strategy? That's how useful they are! Check them out: @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoinnews#tradingview#AItrade