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

Резултати

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

Пребарај: #newindia

当前筛选 #newindia清除筛选
MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #13379 · 14.04.2025 г., 06:44

From Runways to Sky-High Stats ✈️ India’s passenger traffic soars 143% — a testament to rising infrastructure, connectivity & progress! #NewIndia

Hashtags

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12790 · 05.06.2023 г., 13:02

Exciting opportunity to test your knowledge and contribute to nation-building 📝🧾 Take part in the '9 Years of Seva, Sushasan aur Garib Kalyan' Mahaquiz 2023 and celebrate the progress made towards #NewIndia. Visit: https://quiz.mygov.in/quiz/9-years-seva-sushasan-aur-garib-kalyan-mahaquiz-2023/

Hashtags

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12691 · 10.05.2023 г., 08:52

Modern stations for a modern India! With state-of-the-art facilities & world-class amenities, the upgraded railway stations will be a reflection of #NewIndia's progress

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12283 · 09.03.2023 г., 07:09

Capture the transformation of #NewIndia with your lens! Participate in contest and get a chance to win exciting cash prizes Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12181 · 27.02.2023 г., 11:14

Show #NewIndia with your lens! Participate in "Inviting Videos of Transformative Impact" and highlight the benefits received from particular schemes Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12143 · 23.02.2023 г., 15:11

Calling all creative minds to compose a Jingle for the 100th episode of Mann Ki Baat Participate & get a chance to make your jingle remain in the minds and hearts of #NewIndia Visit: https://secure.mygov.in/task/compose-jingle-100th-episode-mann-ki-baat/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12142 · 23.02.2023 г., 14:10

Show #NewIndia with your lens! Participate in "Inviting Videos of Transformative Impact" and highlight the benefits received from particular schemes Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #12118 · 20.02.2023 г., 09:09

Here's a platform to showcase the #NewIndia Share your Before and After videos and describe how a particular scheme of government has benefited you Visit: https://innovateindia.mygov.in/beneficiary-videos/

Hashtags

MyGov Newsdesk

@mygovcoronanewsdesk · Post #11479 · 29.11.2022 г., 08:10

Are you the next best-selling author of #NewIndia? We are looking for you! Apply for YUVA 2.0 and get mentorship, stipend and much more! Know more here : innovateindia.mygov.in/yuva/

Hashtags

123•••10•••20•••2526
ПретходнаСтраница 1 од 26Следна