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

Пребарај: #amitytashkent

当前筛选 #amitytashkent清除筛选
Amity University Tashkent

@amityuniversitytashkent · Post #5138 · 06.11.2025 г., 15:10

#photoreport 😃✨Graduation Vibes at Amity University Tashkent! ✨🎓 On November 6, we proudly celebrated the Graduation Ceremony of the Class of 2025 — a day full of joy, pride, and unforgettable memories! 😍 🎶The event kicked off with the National Anthem of Uzbekistan, setting a proud tone for the celebration. Inspiring speeches followed from Mr. Rustam Karimjonov, Deputy Minister of Digital Technologies of Uzbekistan, and Mr. Amol Chauhan, Senior Vice President of Amity University. 👏 They applauded the dedication and achievements of our graduates and encouraged them to shape the future with passion, creativity, and purpose. 💫 #AmityTashkent#Graduation2025#ProudMoment#AmityFamily 🇺🇿O'zbek tilida 😜Telegram😂Facebook😀Instagram😅Youtube😃Linkedin

Amity University Tashkent

@amityuniversitytashkent · Post #5071 · 25.10.2025 г., 04:21

😀 Heartfelt Congratulations to Dr. Ashok K. Chauhan 🌟 Today, the team of Amity University Tashkent proudly extends its warmest congratulations to Dr. Ashok K. Chauhan, the visionary Founder President of Amity Education Group. Your dedication, wisdom, and lifelong mission to transform education have built a legacy that continues to inspire millions of students across the world. Under your exceptional leadership, Amity has become a global symbol of knowledge, innovation, and human values. Your belief that “Each student must be a success story” resonates deeply with our purpose here in Tashkent and guides us to nurture future leaders with passion and integrity. 💫 We wish you endless energy, good health, and continued success in your noble journey of shaping minds and empowering generations. With deepest respect and admiration, Team of Amity University Tashkent 🇺🇿 #AmityUniversity#AmityTashkent#DrAshokKChauhan#FounderPresident#AmityEducationGroup#GlobalEducation#Leadership#SuccessStory#AmitySpirit#ProudToBeAmity 😜Telegram😂Facebook😀Instagram😅Youtube😃Linkedin