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

Пребарај: #somalis

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

@addisstandardeng · Post #21528 · 26.02.2026 г., 05:18

One-third of #Somalis to face hunger in March: #UN officials Some 6.5 million people, or about a third of Somalia's population, will face crisis levels of hunger through March, an increase of 1.7 million since January, UN officials warned. Speaking to reporters on Wednesday at the UN headquarters via video link, World Food Programme (#WFP) Director of Emergency Preparedness and Response Ross Smith said the latest Integrated Food Security Phase Classification (#IPC) report for Somalia, released on Tuesday, confirmed fears that the humanitarian situation in Somalia has significantly worsened. "Of these, two million of the most vulnerable women and children are expected to face severe hunger," with over 1.8 million children under the age of 5 to face acute malnutrition in 2026, he said. Smith said Somalia is in the midst of a very complex hunger crisis, where two rainy seasons have failed, conflict and insecurity.... https://menafn.com/1110791078/One-Third-Of-Somalis-To-Face-Hunger-In-March-UN-Officials

Addis Standard

@addisstandardeng · Post #22150 · 30.04.2026 г., 10:10

News: #Ethiopian community members in #South_Africa accuse home government of inaction as embassy says engaging authorities Members of the Ethiopian community in South Africa have criticized what they describe as a lack of adequate protection and diplomatic response following recent killings of Ethiopian nationals in Johannesburg, even as #Ethiopia’s embassy in #Pretoria said it is engaging authorities and calling for stronger security measures. The criticism follows a recent shooting in #Johannesburg in which four Ethiopians were killed, with Ethiopian officials saying they are awaiting the outcome of investigations by South African authorities. Speaking to #Addis_Standard on condition of anonymity, a member of the Ethiopian Community in South Africa said the killings of Ethiopians, #Eritreans and #Somalis in South Africa are not new, but warned both the frequency and nature of the attacks appear to be worsening. https://addisstandard.com/?p=56694