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

Резултати

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

Пребарај: #búsqueda

当前筛选 #búsqueda清除筛选
BotsGram®

@botsgram_cu · Post #4294 · 26.08.2021 г., 00:49

¿Que puede hacer este bot? @usetgbot Con este bot puedes buscar diferentes sitios web, directamente desde Telegram Idioma: inglés (Visto en @botsgram_cu) #búsqueda#web

BotsGram®

@botsgram_cu · Post #4331 · 05.09.2021 г., 13:25

¿Que puede hacer este bot? @GooGLeSearchBXBot Con este bot puedes realizar búsquedas en Google de forma inline Idiomas: inglés español (Visto en @botsgram_cu) #google#búsqueda

BotsGram®

@botsgram_cu · Post #3894 · 14.05.2021 г., 01:28

¿Que puede hacer este bot? @podcastly_bot Encuentre nuevos podcasts por sistema de búsqueda o recomendación, envíe notificaciones sobre nuevos episodios. Idiomas: varios incluido español (Visto en @botsgram_cu) #podcasts#búsqueda

BotsGram®

@botsgram_cu · Post #3866 · 04.05.2021 г., 13:01

¿Que puede hacer este bot? @threej_bot Busca canales, grupos, bots y cuestionarios disponibles en el directorio de threej. Idioma: inglés (Visto en @botsgram_cu) #búsqueda#directorio

BotsGram®

@botsgram_cu · Post #4536 · 06.12.2021 г., 14:41

¿Que puede hacer este bot? @BrainQuoteBot Busque citas de personalidades famosas en la mayor base de datos de citas Idiomas: inglés (Visto en @botsgram_cu) #búsqueda#citas#quotes

BotsGram®

@botsgram_cu · Post #4163 · 05.08.2021 г., 14:27

¿Que puede hacer este bot? @faffinitybot Este bot puede buscar información en FilmAffinity sobre películas, series, miniseries, cortos, documentales, etc. Idiomas: español, inglés (Visto en @botsgram_cu) #búsqueda#películas#seies#documentales

BotsGram®

@botsgram_cu · Post #4925 · 11.03.2024 г., 19:50

🤖 Nuevo bot 📋 Nombre: APKFreeDownloader_Bot 🆔 Nombre de usuario: @APKFreeDownloader_Bot ➖➖➖ ℹ️Descripción: ¡Este BOT te ayuda a descargar recursos raros para aplicaciones, juegos o mod apk de forma gratuita! 🌐 Idiomas: Inglés Ruso Español Árabe 💬 Soportes en línea: sí 👥 Grupos: si #️⃣ Etiquetas: #juego#aplicación#apk#android#descargar#búsqueda#enlínea