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

Пребарај: #architecton

当前筛选 #architecton清除筛选

🤑MVP Architec.ton — soon Architec.ton is a platform that brings together dozens of verified gaming projects and their tokens in one place. A space where users can monetize their gaming skills and find like-minded people from all over the world. Presumably, the future application will consist of a separate wallet, a section with games from #Architecton partners, news from the world of the gaming industry and personal user accounts. — Your banks will also be transferred to the new application ✉️What plans next? The platform's core functionality will be steadily expanded and updated. — The team intend to add a section for tournaments, an open trading platform, a rating system for evaluating projects, and many other features that will take games in Telegram to a new level! Get BANK |X | Support

Hashtags

The Digi Doodles

@Digi_doodles · Post #625 · 06.08.2025 г., 10:06

Architecton — Film on Time, Technology & Architecture😐 Director Viktor Kossakovsky’s new documentary is a poetic meditation on the impermanence of modern structures and the enduring strength of architectural heritage🕺 Why watch it? — Cinematic dialogue between past and future — Stunning visuals of ruins and futuristic designs — A reflection on technology’s fleeting touch vs. history’s lasting imprint 🕊It’s more than architecture — it’s a visual essay on civilization’s heartbeat. #Architecton#FilmArt#ViktorKossakovsky#ArtAndTech#CinematicPoetry

☀️AMA-сессия с Лизой Чернягиной 🗓Понедельник, 21 апреля, 18:00 МСК 📍Прямая трансляция в Architec.ton В понедельник у нас в гостях Лиза Чернягина — человек, который строит будущее TON и Telegram: 🔸Автор канала «Опережая тренды» 🔸Создатель первого масштабного курса по разработке в TON и Telegram, который собрал почти 20 000 разработчиков на трёх языках 🔸Основатель венчур билдера LANDAO.VC 🔸Автор нового практического курса по разработке Telegram Apps, о котором мы узнаем первыми! 🔺Темы AMA: 🔸Перспективы экосистемы Telegram на примере WeChat 🔸Какие продуктовые ниши сейчас самые перспективные в Mini Apps? 🔸Как масштабировать обучение Web3-разработке? 🔸Кому и зачем идти в TON и Telegram сегодня? 🔺Темы AMA: 🔸Как экосистема Telegram может повторить путь WeChat? 🔸Какие продуктовые ниши сейчас самые перспективные в Mini Apps? 🔸Как масштабировать обучение Web3-разработке? 🔸Кому и зачем идти в TON сегодня? Подключайтесь, будет мощно: 🔸Живой диалог 🔸Ценные инсайты 🔸Погружение в реальные кейсы из мира TON и образования #ArchitecTon#AMA#TON#TelegramApps#MiniApps#Web3Education#LANDAO#cherniagina#TONDev ☀️MINT | 🔜Wallet | 💬Chat | 📱Channel |📱X | 📱VK | 📱YouTube | 💠Support