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

Резултати

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

Пребарај: #selfreminder

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

@QuietWorld · Post #7507 · 17.07.2020 г., 02:54

Bila kau baru mula bekerja, semalu mana dan serendah diri mana kau rasa pun, anxiety mcm mana pun, beranikan diri bertanya banyak bila tidak tahu sesuatu, itu la privilege jd orang baru. Semalu mana kau rasa untuk bertanya waktu masih baru, bayangkan kalau sudah lama bekerja masih bertanya banyak walaupun berkaitan hal yg lama? Pilih mana satu ☺ #thoughts#selfreminder @quietworld🍃

Quiet World 🍁

@QuietWorld · Post #7277 · 20.04.2020 г., 05:12

I still have me. Don't lose yourself to anyone. There's no use to have a lot of people in your life at the price of losing yourself – because what's the point of having everyone in your life but not having yourself? Don't be afraid to lose people. Instead, be willing to lose people when you need to. #thoughts#selfreminder @quietworld🍃

Quiet World 🍁

@QuietWorld · Post #7255 · 07.04.2020 г., 08:44

Have you ever been in a situation in which you really want to forgive, but your heart can't forgive yet because it still hurts? You really want to forgive but you know you haven't because your heart still aches. & it hurts you more because you still can't forgive. Take your time. Be gentle to your heart. Don't treat your heart like how anyone else treat it. #thoughts#selfreminder@quietworld🍃

Quiet World 🍁

@QuietWorld · Post #7062 · 12.12.2019 г., 02:11

Tbh, you don't have to be the most knowledgable person in the world or anywhere. Knowing that you don't know about somethingyou need to know about and able to decide and take action to find out more about it is enough to help you go a long way. It's just that simple. Remember that. #thoughts#selfreminder @quietworld🍃

123•••67
ПретходнаСтраница 1 од 7Следна