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

Пребарај: #vanlife

当前筛选 #vanlife清除筛选
Иммигранткаст

@immigrantcast · Post #30 · 24.10.2018 г., 07:04

Эпизод 27 - Картонные медведи штата Нью-Йорк https://www.spreaker.com/user/immigrantcast/cardboard-bear-immigrantcast-ep027 Об американских медведах Картонный нарисованный медвед Поездка в поселение Амишей Парковка в Нью-Йорке Стоимость проката машины в Нью-Йорке Поселение людей живущих без электричества в штате Пенсильвания Способы транспорта у амишей Простая религиозно-хипстерская жизнь Airbnb посреди поселения амишей Как амиши зарабатывают на жизнь http://amishamerica.com/how-do-amish-make-money/ Amish Paradise https://youtu.be/lOfZLb33uCg Американская жизнь внутри машины Что делать в Солсбери Краткая история Магна Карты Древнее поселение Старый Сарум Влог из Солсбери https://youtu.be/E1ZqCziVbvs Натуральное органическое молоко на севере Лондона На машине по Long Island Где в Америке можно уснуть за рулем своей машины #vanlife На машине до хипстерского города Вудсток Ночевка на парковке Wallmart В какой машине удобнее всего спать

Hashtags

Urban Dictionary

@urbandictionary · Post #2426 · 21.10.2024 г., 20:00

Van life by Marina 42069 ℹ️Description A bad reference to thug life used by predominantly well off, good looking people who very temporarily live in a van and post lots of selfies hoping to become social influencers. This is nothing like the actual homelessness or poverty that leads people to live in vehicles, it is a privilege similar to the tiny house movement. It relies heavily on photo ops in iconic places that people only learn about on Instagram, not as actual nature enthusiasts. Most #vanlife photos are taken of skinny white blonde women in underpants “having fun” or “ just living a modest life”. 📌Examples “I never knew what true freedom was until I experienced # van life” (selfie caption of young blonde girl in a thong doing yoga) #WordOfTheDay - Source

Auto Life

@revheadcrypto · Post #629 · 08.11.2024 г., 09:31

🚐✨Introducing the Luxurious Brabus Big Boy 1200 Motorhome!✨🚐 This stunning camper, priced at €1.26 million, measures an impressive 12 meters in length and is designed for a maximum of three residents. 🛏️👨‍👩‍👧 The Big Boy 1200 features several retractable modules that expand the living space during your stay, offering a spacious bedroom and a cozy living area that doubles as a dining room. 🛋️🍽️ In the bedroom, you'll find a full-size bed (160x200 cm), while an additional sleeping space for one person is cleverly located above the driver’s cabin. 💤🛌 Built on a robust three-axle Mercedes-Benz Actros chassis, this motorhome is powered by a 12.8-liter diesel engine that delivers an astonishing 530 hp and 2600 Nm of torque! 💪🚛 Get ready to travel in style and comfort! 🌍❤️ #Brabus#BigBoy1200#LuxuryMotorhome#VanLife#TravelInStyle#MercedesBenz#AdventureAwaits#Auto