Использование 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
@JPG2PDFBot
Qué puede hacer este bot?
Envíame fotos JPG o BMP como medios de Telegram.
Cuando hayas terminado,
use /done e intentaré generar un archivo PDF usando las imágenes enviadas en ese orden.
Idioma: Inglés
(visto en @BotsGram_cu)
#pdf, #convert, #photo
@HearForYou_Bot
Qué puede hacer este bot?
Este bot puede Convertir mensajes de audio de Telegram y WhatsApp a texto
Idioma: Inglés
(visto en @BotsGram_cu)
#whatsapp, #telegram, #speachtotext, #convert, #audio
@textUtilsBot
Qué puede hacer este bot?
Bot en línea para transformaciones de texto. Puede ayudarlo a traducir texto del lenguaje humano a código binario o hexadecimal, cadena base64 y viceversa.
Idioma: Inglés
(visto en @BotsGram_cu)
#inline, #utility, #base64, #binary, #hexadecimal, #convert
@NewStickerOptimizerBot
Qué puede hacer este bot?
Simplemente envíeme una imagen o pegatina, y la convertiré en un archivo png y la optimizaré para que su tamaño sea más pequeño o igual a 350Kb, para que pueda agregarlo a un paquete de pegatinas usando el bot @stickers.
Idioma: Inglés
(visto en @BotsGram_cu)
#sticker, #png, #image, #picture, #optimize, #pack, #create, #tool, #convert
#typescript#bun#conversion#convert#converter#document_conversion#elysia#file_conversion#file_converter#hacktoberfest#pdf_converter#self_hosted#tailwindcss#typescript
ConvertX is a self-hosted online file converter that supports over a thousand file formats, including images, videos, documents, e-books, and 3D assets. It lets you convert multiple files at once, offers password protection, and supports multiple user accounts for privacy. You can run it easily using Docker, making it simple to set up on your own server. This means your files stay private since conversions happen locally without sending data to external servers. It uses powerful open-source tools like FFmpeg and ImageMagick, giving you a versatile and secure way to handle all your file conversion needs in one place[1][2].
https://github.com/C4illin/ConvertX
@TelescopyBot
Qué puede hacer este bot?
Con este bot puedes convertir videos cuadrados a videos redondos
Idioma: Inglés, Ruso
(visto en @BotsGram.cu)
#telescope, #video_\message, #convert, #mp4, #gif, #media, #questions, #command, #round, #message, #video