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

Резултати

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

Пребарај: #futureofdriving

当前筛选 #futureofdriving清除筛选
Auto Life

@revheadcrypto · Post #502 · 17.09.2024 г., 15:17

🚗💨Unveiling the Lotus Theory 1: A 1000-HP Marvel!🌟 Get ready to be amazed by the all-carbon supercar that redefines performance! With a compact length of just 4.5 meters, the Theory 1 features a unique door design that lifts up while sliding back. 🚪✨ 🔋Power & Performance: - 1000 HP💥 - 0-100 km/h in just 2.5 seconds⏱️ - Top speed exceeding 320 km/h🚀 - Equipped with a 70 kWh battery for a range of 400 km⚡ - Weighs in at an impressive 1.6 tons⚖️ #LotusTheory1#Supercar#ElectricPerformance#CarEnthusiast#Innovation#FutureOfDriving#LuxuryCars#Auto

Auto Life

@revheadcrypto · Post #453 · 06.09.2024 г., 08:22

🔋✨MG to Launch Electric Car with Solid-State Batteries Ahead of Competitors! The brand's serial models are set to feature these innovative batteries by mid-2025, as announced by SAIC Vice President Yu Jingmin. 🚗⚡️ Preliminary reports suggest that the first model equipped with this cutting-edge technology will be the production version of the recent MG Cyber GTS concept. 🌟 Solid-state batteries offer numerous advantages: reduced size and weight, increased energy density, longer lifespan across a wider temperature range, and a lower risk of ignition. 🔒🔥 #MG#ElectricCars#SolidStateBatteries#Innovation#CyberGTS#FutureOfDriving#Auto

Auto Life

@revheadcrypto · Post #643 · 19.11.2024 г., 10:12

🚗✨ Introducing the Robo X: The Ultimate Battery Supercar! 🚀💨 Get ready to experience mind-blowing acceleration with a stunning 0-100 km/h in just 1.9 seconds! ⚡️🔥 Built on a lightweight carbon and aluminum monocoque, the Robo X weighs in at just 1850 kg. With an impressive estimated range of 650 km, this supercar is designed for both speed and endurance! 🌍🔋 Want to be among the first to own this revolutionary vehicle? Pre-order now with a deposit of 49,999 yuan (approximately 700,000 rubles)! 💰🛒 Production is set to kick off in 2027, so don't miss your chance to be part of the future of automotive innovation! 🏎️💨 #RoboX#Geely#Baidu#Supercar#ElectricVehicle#FutureOfDriving#Innovation#PreOrderNow#Auto