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

Пребарај: #hiddengems

当前筛选 #hiddengems清除筛选

🎬 **Step Back in Time with "Borrowed Wives" (1930): Laughter & Mismatched Marriages!** 🎉 Discover the hilarity of mistaken identities in the pre-Code comedy "Borrowed Wives." This 1930 classic is a must-watch for vintage film lovers! Subscribe now for more timeless gems and exclusive insights! 🌟🍿#ClassicMovies#HiddenGems https://publicdomainmovies.info/borrowed-wives-1930/

**Unleashing the Secrets of *The Leopard Woman* (1920)!** 🎬✨ Step into the exotic world of jungle espionage and adventure! This silent gem stars the charismatic Louise Glaum as the enigmatic Leopard Woman. A spellbinding tale of love and intrigue awaits! 🐆💋 Subscribe now for more classic movie treasures! 🌟#ClassicCinema#HiddenGems https://publicdomainmovies.info/leopard-woman-1920/

🏨 ACCOMMODATION SECRETS: ETHIOPIA'S HIDDEN GEMS | ድንቅ የሆኑ የኢትዮጵያ ማረፊያ ቦታዎች 🌟 From royal palaces to mountain hideaways - discover where legends stay in the Horn of Africa. 🏨 LUXURY HOTELS | ቅንጡ ሆቴሎች • Sheraton Addis: $200-300/night, presidential suite where Obama stayed • Hyatt Regency: $150-250/night, rooftop views of Entoto Mountains • Radisson Blu: $120-200/night, modern amenities in heart of city • Four Points Sheraton: $100-180/night, business traveler favorite 🏡 TRADITIONAL GUESTHOUSES | ባህላዊ እንግዳ ማረፊያዎች • Yod Abyssinia: $60-80/night, authentic Ethiopian architecture • Taitu Hotel: $40-70/night, historic charm in Piazza district • Local family homestays: $15-30/night, genuine cultural immersion • Traditional tukuls: $25-50/night, round stone houses with thatched roofs 🏔️ ECO-LODGES & WILDERNESS | ተፈጥሮ ተስማሚ ስፍራዎች • Simien Lodge: $180-250/night, gelada monkeys at your doorstep • Buska Lodge (Omo Valley): $120-200/night, tribal cultural experience • Danakil camping: $40-80/night, sleep under Milky Way in Mars landscape • Lalibela mountain lodges: $80-150/night, rock churches views 💰 BUDGET ACCOMMODATIONS | የእርስዎን በጀት ያማከሉ ማረፊያዎች • Backpacker hostels: $8-15/night, shared dorms with Wi-Fi • Pension houses: $12-25/night, family-run, breakfast included • Government rest houses: $5-12/night, basic but clean • Church compounds: $3-8/night, unique spiritual experience 📱 BOOKING PLATFORMS & TIPS • Best platforms: Booking.com, Agoda, local Ethiopian sites • Direct booking: Often 10-20% cheaper, call hotels directly • Peak seasons: Christmas (Jan 7), Timkat (Jan 19), Meskel (Sept) • Negotiation: Always possible except peak times 💡 INSIDER SECRETS: Book mountain lodges 2+ months ahead. Many hotels accept USD directly. Traditional coffee ceremony often included. Ask for "faranji price" vs local rate. 🏆 From $3 sacred sanctuaries to $300 presidential suites - Ethiopia accommodates every dream! #EthiopiaHotels#ኢትዮጵያ#Accommodation#TravelSecrets#HiddenGems