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

Резултати

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

Пребарај: #messages

当前筛选 #messages清除筛选
1 English learning materials

@englishmeta1 · Post #39 · 13.02.2022 г., 15:36

Valentine's Day Messages: .1All I wanted was someone to care for me, All I wanted was someone who'd b there for me, All I ever wanted was someone who'd b true, All I ever wanted was someone like You! Happy Valentine's Day! 2.A day filled with kisses, a week filled with romance, a month filled with love, a year filled with bliss and a lifetime filled with happy memories. I want to spend the rest of my life with you. Happy Valentine’s Day! 3.Darling, my love for you is as deep as the sea and as high as the sky. Happy Valentine’s Day! When I look at you, I’m amazed by your beauty, both on the outside and the inside. Happy Valentine’s Day! 4.I still remember the moment when our eyes met for the first time. I felt butterflies in my stomach and since then my heart longs to be with you always. Be mine forever! 5.A day without you is a day without a sun, a night without a moon; a life without meaning. 6.Happy Valentine’s Day to the most special person in my life. You are my love, my heart and my joy. #Messages #Teamjimmy #sirjimmy

🎨 𝗧𝗘𝗠𝗔𝗦 𝗧𝗘𝗟𝗘𝗚𝗥𝗔𝗠 ➤ 𝗧𝗚𝗫 📢 𝗖𝗵𝗮𝗻𝗻𝗲𝗹: @DNZ_Temas ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ 🔗𝗔𝗣𝗣𝗟𝗬 𝗧𝗛𝗘𝗠𝗘>> 𝕋𝔼𝕃𝔼𝔾ℝ𝔸𝕄 ✅ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ ➖ 🏷️Tags: #Dark#Google#Messages ╚═══ ღ 𝔻ℕℤ 𝕋𝔼𝕄𝔸𝕊 ღ ═══╝

BotsGram®

@botsgram_cu · Post #3217 · 30.11.2020 г., 21:31

@GitHubBot Qué puede hacer este bot? Este es un bot de GitHub. Puede notificarle sobre eventos en sus repositorios públicos de GitHub. También puede responder a tus mensajes para publicar comentarios en GitHub directamente desde Telegram. Idioma: Inglés (visto en @BotsGram_cu) #telegram, #notify, #events, #github, #delete, #public, #command, #messages, #repository

BotsGram®

@botsgram_cu · Post #3233 · 04.12.2020 г., 02:27

@junction_bot Qué puede hacer este bot? Este bot puede recopilar publicaciones de tus canales favoritos de Telegram, para que puedas leerlas como un servicio de noticias. ¡También puede copiar mensajes entre canales y bots, filtrar anuncios, modificar mensajes y mucho más! Idioma: Inglés, Ruso, Turco (visto en @BotsGram_cu) #link, #word, #project, #feed, #messages, #group, #subscription, #telegram, #share, #channel, #questions, #command, #inline, #join, #twitter, #favorite, #collect, #news, #enter, #place, #free, #message, #welcome