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

Резултати

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

Пребарај: #rapidresponse

当前筛选 #rapidresponse清除筛选
DOW Rapid Response

@DOWResponse · Post #4 · 10.09.2025 г., 13:29

🚨 OFFICIAL ANNOUNCEMENT 🚨 Welcome to the Rapid Response Channel of the Department of War (DOW). This is the first and only official account dedicated to: ⚔️ Supporting the mission and vision of@SecWar ⚔️ Delivering rapid, fact-based updates in real time ⚔️ Exposing disinformation and defeating fake news ⚔️ Defending truth, clarity, and the mission of national security The fight for truth begins here. The DOW Rapid Response team is on watch — always ready, always accurate, always first. Follow. Engage. Share. Stand with us. 🛡️ #DOW#RapidResponse#SecWar https://t.me/DOWResponse✅

HHS Rapid Response

@HHSResponse · Post #4 · 29.10.2025 г., 20:59

🔹🔷Welcome to the Official HHS Rapid Response Channel 🔷🔹 This is the official @HHSgovv Rapid Response account, working every day to support President Trump’s and Secretary Kennedy’s mission to Make America Healthy Again (MAHA). 🇺🇸 Here, we deliver real facts, rapid updates, and clear information to cut through misinformation and ensure the American people get the truth they deserve. Health is strength. Truth is power. Together, we will Make America Healthy Again.💪 Stay tuned for verified updates, fact checks, and official responses from the U.S. Department of Health and Human Services. #RapidResponse | #MAHA | #HHS | #PublicHealth | #TruthMatters 📱https://t.me/HHSResponse✅️