TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #397 · 12 ное.

Использование 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

Резултати

Пронајдени 3 слични објави

Пребарај: #vanquish

当前筛选 #vanquish清除筛选
Новости из Сербии

@NewsSerbia · Post #13321 · 19.03.2026 г., 07:42

Самый дорогой экспонат Белградского автосалона – Aston Martin Vanquish Volante Этот роскошный кабриолет ярко-синего цвета является одной из главных звезд выставки, впервые официально представляя бренд Aston Martin на Белградской ярмарке. Двигатель: 5,2-литра битурбо V12. Мощность: 835 л. с. Разгон до 100 км/ч: 3,4 секунды. Максимальная скорость: 345 км/ч. Пока мир переходит на электрокары, Aston Martin привозит на автошоу в Сербию бензиновое безумие с мотором V12. 💰 Цена вопроса: 500 000€ #AstonMartin#Vanquish#Белград#Сербия @NewsSerbia

Auto Life

@revheadcrypto · Post #433 · 04.09.2024 г., 16:41

🚗✨ Introducing the new Aston Martin Vanquish with a powerful V12! 🌟 🔧 Equipped with a twin-turbo engine delivering an impressive 835 hp and 1000 Nm of torque (just edging out the Ferrari 12Cilindri at 830 hp)! 💪 ⚡️ Accelerating from 0 to 60 mph (96 km/h) in just 3.2 seconds, this flagship beauty boasts a top speed of 344 km/h! 🏁 🛠️ The Vanquish features a brand new body with a 75% increase in stiffness compared to the DBS. It comes with carbon-ceramic brakes and cutting-edge Bilstein DTX adaptive dampers for an unparalleled driving experience! 🚀 📅 Deliveries of this grand tourer will begin in Q4, with a starting price of $420,000. 💰 #AstonMartin#Vanquish#V12#LuxuryCars#Performance#CarEnthusiasts#Supercar#DrivingExperience#Auto

Auto Life

@revheadcrypto · Post #418 · 01.09.2024 г., 10:09

🚗✨For Sale: Aston Martin Vanquish!✨🚗 This stunning grand tourer isn't just any car; it was featured in a promotional photoshoot for the James Bond film "Die Another Day" starring Pierce Brosnan! 🌟 🔹Power: 460 HP 🔹Mileage: Over 60,000 km 🔹Price: Up to $100,000 Don't miss your chance to own a piece of cinematic history! 🎬💎 #AstonMartin#Vanquish#JamesBond#DieAnotherDay#LuxuryCars#CarForSale#BondCar#DreamCar#Auto