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

Резултати

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

Пребарај: #rm

当前筛选 #rm清除筛选
Bts.bighitofficial

@OUR_7_PRINCES · Post #114718 · 19.07.2025 г., 16:43

Tae Hoon Lee (Nike’s Korea Marketing Director) shared a picture of #RM with J-Hope and Suga at the wedding. #INFO •@OUR_7_PRINCES•

Hashtags

Bts.bighitofficial

@OUR_7_PRINCES · Post #113772 · 18.06.2025 г., 23:26

#RM via Amalia Wirjono (Museum MACAN's Head of Development) instagram. https://www.instagram.com/p/DLDS91PTkYX/?igsh=aGU2ZXc2bGk2cGw2 #INFO •@OUR_7_PRINCES•

Hashtags

Bts.bighitofficial

@OUR_7_PRINCES · Post #115031 · 01.08.2025 г., 08:42

RM INSTAGRAM STORY UPDATE 💜 Translation Weren’t you curious? You must have been very curious. But writing is something you keep doing because you think you can’t help it, even if you won’t become a good writer. They probably kept writing, and by doing so, they became writers. Now they are probably getting asked the same question I get: ‘Did you always think you’d become a writer?’ If you live like a useless boat drifting with the tide, you eventually arrive somewhere. That is the future. And it comes even if you do nothing. When you finally reach that future, there is something everyone does—rewrite the preface of the past to match the ending [this quote is from a book. It’s attributed to Kim Young-ha (김영하) and appears in his novel A Single Life (단 한 번의 삶) .] #RM | #INSTAGRAM •@OUR_7_PRINCES•

Bts.bighitofficial

@OUR_7_PRINCES · Post #114715 · 19.07.2025 г., 16:42

#RM via rkive repost: 1. Eyes Magazine editor Jin Pyo: “Kim euri @ rkive You’re really a good host/MC.” 2. Post Archive Fasion Creative Director Lim Dongjoon: “You're the best MC/host I've ever seen...” #RM | #INSTAGRAM •@OUR_7_PRINCES•

ПретходнаСтраница 1 од 4Следна