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 слични објави

Пребарај: #hassan

当前筛选 #hassan清除筛选
Addis Standard

@addisstandardeng · Post #21313 · 05.02.2026 г., 05:34

#Somali president orders urgent drought response as famine fears grow Somali President #Hassan Sheikh Mohamud on Wednesday ordered all government institutions to prioritise emergency drought response after visiting the National Disaster Management Agency’s emergency operations centre. The president received a detailed briefing from agency officials on the worsening drought, including the hardest-hit areas, displacement, environmental degradation and reported loss of life. Officials warned the crisis had reached a critical stage and risked tipping into famine if urgent action is not taken. Mohamud called on government officials, Somali business leaders, humanitarian organisations and international partners to unite in responding to the growing humanitarian emergency and to prevent further human suffering. He also instructed the country’s financial authorities to exempt from taxes all aid, donations and.... https://shabellemedia.com/somali-president-orders-urgent-drought-response-as-famine-fears-grow/

Addis Standard

@addisstandardeng · Post #21378 · 12.02.2026 г., 08:30

News: #Somali president witnesses #Egyptian troop deployment to AU mission in Somalia Somali President #Hassan Sheikh Mohamud has witnessed the formation of Egyptian forces assigned to the #African_Union Support and Stabilization Mission in Somalia (#AUSSOM), according to a report by Egypt Today, citing a statement from Egypt’s military spokesman. The formation ceremony was attended by Egypt’s Minister of Defense and Military Production Gen. Abdel Mageed Saqr, Chief of Staff Lt. Gen. Ahmed Khalifa, and senior Egyptian military commanders. The military spokesman said the visit included briefings on the preparation, equipping, and operational readiness of Egyptian troops designated for the mission. The program also featured training exercises and a display of vehicles intended for deployment, with officials stating the forces had completed intensive professional training to ensure.... https://web.facebook.com/AddisstandardEng/posts/pfbid02D7ibS3RJJRGZzoYDziFEYk4VKn5vmQXDQVkAtLaU2C4EuxFtVrj8HUbHXYrD4eFSl