Использование 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
A map of the Israeli Airstrikes on the Lebanese Beqaa region that took the lives of 63 civilians and i jured more than 100 people in a raid of more than 100 airstrikes targeting the region.
#LebanonUnderAttack
Genocidal Psychopaths of the Zionist Israeli terrorist army blow up the entire Lebanese bordering Village of Mhaybeeb this morning on October 16, 2024.
#LebanonUnderAttack
#Israel carried out a large-scale massacre today, November 1, 2024, in the Lebanese towns of Baalbek district. 52 people were killed, 72 wounded, and 9 remain missing after 25 airstrikes by Israeli warplanes conducted over two hours, from 2 p.m. to 4 p.m.
#LebanonUnderAttack
Even in the darkest times of #war, humor becomes a tool for resilience, offering brief moments of relief and a way to cope with the harsh realities. It’s a reminder that laughter, no matter how fleeting, can be a powerful act of defiance and hope in the face of adversity.
#LebanonUnderAttack
The Lebanese Ministry of Health's Emergency Operations Center reported that the death toll from the Israeli assault has climbed to 2,653, with 12,360 others wounded since October 8, 2023. This staggering rise reflects the continuous bombardment and escalating violence.
#Israel#Lebanon#LebanonUnderAttack
#Hezbollah carried out a series of coordinated rocket and drone attacks, targeting Israeli military sites, gatherings, and settlements. The operations resulted in casualties and showcased the group's ongoing military capabilities.
#LebanonUnderAttack#Israel
#Israel conducted heavy airstrikes overnight in #Beirut suburbs on the Mreijeh area taking out an entire neighborhood turning it to rubble.
#LebanonUnderAttack
Israel has struck Beirut once again, this time targeting Mar Elias Street; the heart of the capital and one of its most densely populated areas during the war, as countless displaced families from the suburbs have sought refuge there.
This relentless aggression is not just an attack on civilians; it’s a blatant violation of all norms of international law, crossing every red line.
#LebanonUnderAttack
#BeirutUnderAttack
Zionist Israeli Psychopaths hit a home in Ayto town in #Zgharta north #Lebanon that was housing families displaced from South Lebanon and Beirut suburbs. 25 humans in the house, the Red cross so far said that 18 are martyred.
I will not share any videos or photos, as many of the women might be hijabis, and the footage shows them in heartbreaking scenes without their hijabs.
#LebanonUnderAttack
Devastation in the heart of Beirut: On the night of November 17, #Israel targeted a densely populated building on the famous Mar Elias Street, setting off a massive fire that raged through the night. The building housed motor generators and an electronics shop, where lithium batteries likely fueled the inferno, adding to the chaos and destruction.
#LebanonUnderAttack#WarCrimes#Beirut
Ophthalmologist MP Elias Jradeh reveals that a blockade was imposed on Lebanon regarding the import of corneas after the Pagers bombing, which led to their disappearance from the local market and harmed various Lebanese citizens.
#Lebanon#PagersAttack#Hezbollah#LebanonUnderAttack
In a heartbreaking video, Julia shared moments while she was playing the piano in her home in Khiam, South Lebanon, which she discovered in a video circulated by Israeli soldiers that was destroyed during the border clashes when they were attempting to occupy her town.
#SouthLebanon#Khiam#LebanonUnderAttack#Israel