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 слични објави

Пребарај: #electriccrossover

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

@revheadcrypto · Post #106 · 15.07.2024 г., 08:05

🚘Introducing the all-new Honda Ye S7 electric crossover! 🌿 🔋 Two-motor powertrain: 476 hp total power. Front wheels driven by a 204-hp electric motor, while the rear wheels by a 272-hp motor. 🏞️ Built on the e:N Architecture W platform with independent suspension, this 4.7-meter crossover promises a smooth ride. 🔌 Co-developed with Dongfeng, the Ye S7 is set to redefine the electric SUV experience.⚡️ #HondaYeS7#ElectricCrossover#Innovation#Auto

Auto Life

@revheadcrypto · Post #324 · 16.08.2024 г., 19:05

🌟🚗 Introducing the Genesis GV90! 🚗🌟 Get ready for the flagship electric crossover from Genesis, set to debut this October! 🎉✨ Built on the innovative eM platform, an evolution of the E-GMP architecture, the GV90 promises an impressive 113 kWh battery that offers a remarkable range of up to 800 km!🔋🌍 With its luxurious design and advanced features, the GV90 will compete with premium full-size SUVs like the Range Rover. 🏞️👑🚀 #GenesisGV90#ElectricCrossover#LuxurySUV#eMPlatform#Auto🌐🔋✨

Auto Life

@revheadcrypto · Post #545 · 02.10.2024 г., 09:34

🚘✨Introducing the Skoda Elroq Electric Crossover!✨🚘 The new Skoda Elroq is slightly larger than the Karoq, measuring 4488x1884x1625 mm with a wheelbase of 2765 mm. With a ground clearance of 186 mm, it’s ready for any adventure! 🌍💪 ⚡️Performance Features: - Available with electric motors producing 170, 204, or 286 hp. - The top all-wheel-drive version boasts an impressive 299 hp! 🚀 - Range: From 375 to 560 km on a single charge! 🔋🌿 ✅Simply Clever Innovations: - Tire tread depth gauge integrated into the ice scraper! ❄️ - Elastic net under the luggage shelf for convenient charging cable storage! 📦🔌 ℹ️ The petrol Karoq starts at €33,100 in Germany, while the Elroq will be just €760 more! 💰🇩🇪 #SkodaElroq#ElectricCrossover#SimplyClever#SustainableDriving#CarLaunch#Auto#Innovation#Skoda