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

Резултати

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

Пребарај: #callegrambusiness

当前筛选 #callegrambusiness清除筛选
@Call News

@call_updates · Post #46 · 08.05.2024 г., 07:05

ℹ️How Callegram Business Works Right Now In previous post we told you how to setup a Callegram Business account. Today we're sharing with you what you'll get after new status: ⚙️Notifications Settings. When your customer will book a call, you can setup a specific time presets for notifications. To find all notification settings you can view Profile section inside @CallegramBot Mini App; 💬Automated Replies. At this moment your schedule is sent when your customer asks you about it. If in customer's questions will contain these words: «Schedule, Appointment, Booking, Book» — @CallegramBot will send your schedule instantly. Check the video above to see how it works. Ask us anything about Callegram Business and we will help you! #CallegramBusiness#MiniApps#Business

@Call News

@call_updates · Post #44 · 22.04.2024 г., 15:00

ℹ️How to Setup Callegram Business 1. Open Telegram settings; 2. Tap on «Telegram Business» button; 3. Find «Chat Bots» section; 4. Enter CallegramBot into special field and tap on the button «Add» ✔️ Done. Now your Callegram profile is in Business mode. ⚙️ Don't forget to setup your working hours in Telegram Business menu. #CallegramBusiness#Business#MiniApps

@Call News

@call_updates · Post #50 · 22.05.2024 г., 13:05

👍 Make Us Better We've been growing fast and we want to give you the best experience if you use @CallegramBot. We've sent a special feedback form to all our Business users. If you want to help us make Callegram better, please fill in the form below: 🔗https://t.me/CallegramBot/feedback P.S. Don't forget share with us your the most desirable function #TelegramBusiness#CallegramBusiness#MiniApps#Web_Apps