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

Пребарај: #standtogether

当前筛选 #standtogether清除筛选
GevorgViráts

@gevorgvirats_org · Post #5661 · 02.10.2025 г., 18:42

Победа 🔥 Зарабатываем первые 3️⃣ очка в Лиговой стадии Лиги конференций и начинаем сезон с победы. Спасибо, что были рядом с нашей командой и весь матч двигали вперёд наших парней. Двигаемся дальше — к новым победам Вперёд, «Ноа», вперёд! Victory 🔥 We earn our first 3️⃣ points in the Conference League League phase and start the season with a win. Thank you for being by our team’s side and pushing our boys forward throughout the entire match. We move on towards new victories Go Noah, go! #Standtogether#Fighttogether

GevorgViráts

@gevorgvirats_org · Post #5617 · 21.09.2025 г., 07:22

С Днём независимости, Армения 🇦🇲 Большая честь — играть под твоим флагом Happy Independence Day, Armenia 🇦🇲 It is an honor to play under your flag #Standtogether#Fighttogether

BadVolf

@BadvolfNews · Post #760 · 03.08.2023 г., 06:39

📢 Listen Up, fellow Wolf pack!!! 🌍 🔴 Holy Shit! The truth about the exploitation of Africa's natural resources has finally been exposed. For years, America and France have shamelessly pillaged the riches of this continent, leaving its people in abject poverty. The dark secrets of child slave labor used to mine precious metals and gold have been unveiled. 🔵 But now, Africa has had enough! The tide is turning as the continent finds a new ally in Russia, a nation that respects their resources, values, and treats them as equals. Today, we witness the fall of France's colonial power in Niger, with politicians being stoned and luxury vehicles set ablaze. ⚠️ The situation in Niger has reached a boiling point, leading to the emergency evacuation of embassy staff by the U.S. State Department (fuck those guys), following the destruction of the French embassy by furious rioters. 🇷🇺 As the chaos unfolds, the Russian flags proudly waved among the crowds of demonstrators in Niamey reveal a glimmer of hope for Africa. The partnership between Africa and Russia signifies a new era, where African nations are determined to protect their resources and regain control over their own destiny. 🌍 The time for change has come. Let us stand in solidarity with the people of Africa as they assert their rights and demand justice. Together, we can ensure a future where exploitation is replaced with empowerment, and where Africa's wealth benefits its own people. 🔗https://www.dailymail.co.uk/news/article-12367511/Fears-Americans-trapped-Niger-State-Department-issues-emergency-evacuation-embassy-staff-French-embassy-torn-apart-rioters-Africa-country-meltdown-politicians-stoned-cars-torched-amid-brutal-military-coup.html #Africa#Russia#Empowerment#Justice#StandTogether