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

Резултати

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

Пребарај: #meditation

当前筛选 #meditation清除筛选
Quiet World 🍁

@QuietWorld · Post #8016 · 24.02.2022 г., 01:37

Pulled a card for messages regarding yesterday & I got the card “Stop fuvking whining.” 😂 “No one wants to listen to that shit. Complaining makes you weak. You have the strength to change your world; so do it.” Thank you for the message, Spirit Guides ☺️ Imma pick myself back as usual. I may not always have people to be there for me whenever I'm down but I always can count on my angels & Spirit Guides. I have an army of my spiritual team around me that always have my back. We all do. Isn't that the best thing ever? They can do what humans can't do. #thoughts#meditation#tarot#oracle@quietworld🍃

Quiet World 🍁

@QuietWorld · Post #7644 · 19.10.2020 г., 02:38

Have you ever heard of Memory Palace Technique? – a technique in studying that helps you remember what you learn better and faster? Well, I'm using that technique, but not in studying; but in reminding myself of gratitude and encouraging positive self affirmation with crystals. One thing for sure, ever since I get myself involved in crystals (since July to be precised), I'm coping with my self-esteem, motivation & anxiety, better. Interested? Check out Ponderlog for more 😘 #ponderlog#crystallovers#grootcrystal#meditation#selfhealing#crystalhealing#crystalmeditation#memory#reminder#mindbodyspirit

Ничего особо не видел. Туман был сильный. #travel#foodie#fitness#art#music#photography#nature#fashion#beauty#motivation#quotes#books#coffee#technology#gaming#movies#design#architecture#cars#motorcycles#space#science#history#culture#streetstyle#selfcare#mindfulness#yoga#meditation#business#entrepreneur#marketing#startup#coding#ai#robotics#education#learning#languages#writing#poetry#drawing#painting#digitalart#illustration#animals#cats#dogs#wildlife#ocean#mountains#sunset#sunrise#citylife#streetphotography#minimalism#vintage#retro#luxury#watches#sneakers#streetwear#makeup#skincare#healthyfood#vegan#recipes#baking#gardening#plants#flowers#home#interior#decor#lifestyle#adventure#explore