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

Резултати

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

Пребарај: #merisarkar

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

@MyGovCoronaNewsdesk · Post #12668 · 04.05.2023 г., 06:05

India's mobile manufacturing sector has come a long way! Thanks to government initiatives like PLI, Make in India, and Digital India, India's tech sector is leading the way towards self-reliance. India is no longer dependent on mobile imports. #MeriSarkar

Hashtags

कोविड-19 महामारी के समय ₹31,000 करोड़ सीधे जन धन योजना की महिला लाभार्थियों के बैंक खातों में हस्तांतरित किए गए। #MeriSarkar #JanDhanYojana

#JanDhanYojana केवल बैंक खाते खोलने के बारे में नहीं है; बल्कि यह नई संभावनाओं का द्वार है और इसने करोड़ों महिला लाभार्थियों के जीवन को आसान बनाया है। #MeriSarkar

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12667 · 04.05.2023 г., 05:04

Proud moment for India's mobile manufacturing industry! The world is increasingly choosing Made in India mobiles, a testament to the country's quality and innovation in the tech sector. #MeriSarkar #PaiPaiSeDeshKiBhalai

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12664 · 03.05.2023 г., 18:02

Global giants have expanded their operations, showing immense confidence in India’s growth story. It has boosted job opportunities and paved the way for India’s digital transformation. #MeriSarkar #PaiPaiSeDeshKiBhalai

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12514 · 11.04.2023 г., 11:02

The world is recognising the success of Jan Dhan Yojana. India has become a global leader paving the way for financial inclusion at a massive scale and speed. #MeriSarkar #JanDhanYojana

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12512 · 11.04.2023 г., 08:58

In the most unprecedented circumstances like the Covid-19 pandemic, Rs 31,000 crore were directly transferred into the bank accounts of Jan Dhan Yojana women beneficiaries. #MeriSarkar #JanDhanYojana

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12510 · 10.04.2023 г., 16:17

Jan Dhan Yojana is not just about opening bank accounts; it is a door to new possibilities and has ensured ease of living for crores of women beneficiaries. #MeriSarkar #JanDhanYojana

MyGov Newsdesk

@MyGovCoronaNewsdesk · Post #12666 · 04.05.2023 г., 04:04

India's mobile manufacturing sector is becoming #Aatmanirbhar! PLI is driving growth in the mobile manufacturing sector, making India a leader in mobile production and creating new opportunities for domestic players. #MeriSarkar

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