Использование 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
#LINEAопубликовали чекер эйрдропа
Проверить дроп можно по ссылке
Клейм должны открыть 10 сентября в 11:00 по МСК
Ключевые моменты дропа:
- Минимальный порог для участия: 2,000 LXP
- Распределенено - 9.361 млрд $LINEA
- Допущенные адреса - 749,663
- Семь уровней с прогрессивным вознаграждением:
Tier 1: 2,000 LXP
Tier 2: 3,000 LXP
Tier 3: 4,000 LXP
Tier 4: 4,500 LXP
Tier 5: 5,000 LXP
Tier 6: 6,500 LXP
Tier 7: 8,000+ LXP
- Внутри уровня - линейное распределение, чтобы более активные участники получали больше
Цена $LINEA на премаркете: ≈ 0.034$
Кто крутил линею? Кому сколько насыпали?
Welcome to Linea Culture SZN😎
🎨 Find the entrance on TokenPocket's DApp Store, you can easily participate in #Linea Culture SZN on layer3xyz and find your Fam in a snap! 🎊
📱Discover page > Airdrop Zone
💻Open TokenPocket's DApp Store > Airdrop Zone
👉https://tokenpocket.pro/en/dappstore?category_id=99998&category=Trend
All-in-one, all in TokenPocket!
👉https://tokenpocket.pro
Are you human? Linea wants to know 📞
Prove that your #Linea Score leveled up! Nomis and Intract deliver this chance
📸 Meet PROOF-OF-LINEA OG: Two stages, two weeks, x2 rewards
Start Here —->
🔗Start Here
The flow is simple:
Stage 1 on Intract ->
🔗Start Stage 1
1. Verify your updated Linea Rep Score, powered by Nomis.
(If you have the old version, update it on Intract with a 50% discount to get the new one)
2. Complete social tasks.
Stage 2 on the Gravity, Nomis Platform ->
🔗Go to Stage 2
1. Use your Linea Score as a passkey
2. Obtain the PoH Medallion, powered by Intract (it's free)
3. Complete social tasks.
What you get: Intract 3 gems/user, Nomis x2 points, and 2FA verification. YOU ARE ✨ HUMAN ✨
💠Nomis tApp | X | Discord | YouTube | Check Scores⚖️
Every Nomis Score packs its own punch when it comes to benefits 🧐
For example, Linea Rep Score
🌟 Over 500K users farmed their LXP (token-convertible) through Linea Park and Linea Voyage because the Linea Score serves as a rewards ticket!
✍️ We've broken down #Linea Score for you:
• What it is
• What it unlocks
• How to make it work for you
READ THE ARTICLE 👨💻
And NOW, you have the opportunity to leverage your Score in Life on Linea:
1. Get your Linea Score
2. Visit Gravity
3. Harvest LXP with Izumi Finance
4. Gather Gravity points
5. Claim your slice of the $3k reward pool 🤑
All gain, no pain: your turn 🫵
🆕Lynex now fully supports #TokenPocket login! LynexFi
✅Lynex is LineaBuild's native on-chain liquidity marketplace. Powered by cutting-edge DEX infrastructure, it offers a highly capital-efficient DeFi solution. #Linea
🔥You can access Lynex with your TokenPocket wallet. (Both Mobile Wallet and Chrome Extension)
👉https://www.tokenpocket.pro/
👉https://app.lynex.fi/
【Details】https://twitter.com/TokenPocket_TP/status/1750718245525701079
【Powered By】Crypto Box
$3K + $5K = MBV 8 Celebration & Life on Linea Quests hosted by Nomis ❤️
The smartest move to leverage your #BNB and #Linea Reputation Scores is to get rewarded for it 👻
- 10+ partners
- Eco perks
- POINTS, POINTS, POINTS
Only YOU, your Score, and rewards ⚡️
In community we trust, in BUIDLers we build
💜
Proud to build and lead as the top Proof-of-Humanity protocol on Linea #blockchain!
Discover our Linea Reputation Score's Core and our achievements on Linea in the new YouTube video:
- What is Linea Score
- What parameters it counts
- How to get it
- How to leverage it
👉WATCH THE VIDEO HERE 👈
Don't forget to jump on Life on Linea Quest on Gravity 👽
- Prepare your #Linea Score
- Complete tasks
- Earn points 🪂
We'll distribute $3K among the users with the highest results (points + Score)
LFG 🫵