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

Резултати

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

Пребарај: #convertible

当前筛选 #convertible清除筛选
Car News

@car_news · Post #618 · 09.10.2024 г., 17:35

🚘 has presented modernized coupe and convertible LC The model range, produced since 2017, got slightly modernized exterior and new interior materials, but at the same time received a more rigid body. Additional struts installed under the floor in the area of the front and rear axles should favorably affect the handling. The Lexus LC engine range consists of a five-liter V8 with 477 horsepower or a 3.5-liter V6-based hybrid unit with 359 hp. Starting from $107,625. @CarsNews #Lexus#hybrid#convertible

Auto Life

@revheadcrypto · Post #298 · 10.08.2024 г., 12:16

🚗✨ Exciting News from Mercedes-Maybach! ✨🚗 Get ready for the debut of the stunning new convertible on August 15th at the prestigious Pebble Beach! 🌊🏖️ The highly anticipated model has been teased since 2022, and we can't wait to see it in all its glory! 🤩 🔍 Fuel Efficiency: The Mercedes-Maybach SL boasts an impressive fuel consumption of 13.7 liters per 100 km*, closely matching the non-hybrid Mercedes-AMG SL 63 with its powerful 4.0L V8 engine, delivering a thrilling 585 hp and 800 Nm* of torque! 💨🔥 #MercedesMaybach#Convertible#LuxuryCars#PebbleBeach#CarDebut#FuelEfficiency#AMG#V8Power#Auto