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

Резултати

Пронајдени 22 слични објави

Пребарај: #superheroes

当前筛选 #superheroes清除筛选
movies & series 🍿

@images · Post #1543 · 30.05.2024 г., 13:43

🍿 The Last Adventure of 'The Umbrella Academy'! 📆Premiere: August 8, 2024 🎭Genre: #Superheroes · #Drama The Hargreeves return for one final mission in the fourth and last season of 'The Umbrella Academy'. This time, without their powers, they must adapt to normal life, though chaos still ensues. 🌀 Elliot Page, Tom Hopper, and the rest of the original cast are back, along with new additions Nick Offerman and Megan Mullally. The curious part: the Thibedeaus, college professors with extreme déjà vu! 🤯 Reginald Hargreeves is back, leading a dark empire, while a mysterious organization believes reality is a lie. Don’t miss the trailer set to 'The Final Countdown'. 🎬💥 > 𝘴𝘦𝘳𝘪𝘦𝘴 · 🚀𝘣𝘰𝘰𝘴𝘵

movies & series 🍿

@images · Post #1746 · 20.12.2024 г., 08:54

🍿 Superman: Legacy, the Rebirth of Hope ☀️ 📆Release: July 11, 2025 🎭Genre: #Action · #Fantasy · #Superheroes I just watched the trailer, and I’m filled with excitement. James Gunn’s Superman (Guardians of the Galaxy) focuses on kindness. David Corenswet (Hollywood) dons a colorful suit, flying and shielding a little girl. Rachel Brosnahan (The Marvelous Mrs. Maisel) brings a spark to Lois Lane, while Nicholas Hoult (Mad Max: Fury Road) promises a compelling Lex Luthor. Guy Gardner, with his bowl cut, couldn’t be more perfect. And Krypto, that dog, melts my heart. This movie looks like it’ll radiate optimism, reminding us that the world needs heroes who inspire. I can’t wait to see it. 🎉

12
ПретходнаСтраница 1 од 2Следна