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

Пребарај: #auc

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

@addisstandardeng · Post #21878 · 30.03.2026 г., 05:16

News: #AU chairperson urges dialogue, restraint amid rising tensions in #Somalia’s Southwest State The African Union Commission (#AUC) Chairperson, Mahmoud Ali Youssouf, has called for dialogue and restraint among Somali stakeholders amid rising tensions in the #Southwest State of Somalia. In a statement released by the AUC, the Chairperson said he is closely monitoring developments in the region and expressed concern over escalating tensions and their potential impact on the country’s stability, security, unity, and humanitarian situation. He underscored the importance of the National Consultative Council as a key platform for inclusive dialogue and consensus-building, urging all parties to make constructive use of it to resolve differences peacefully. The statement emphasized that disputes between the Federal Government and Federal Member States should be ....... https://www.facebook.com/AddisstandardEng/posts/pfbid0s5reSjXyuiniXuYjiot3AckwjHmjs6TqtDhGeL7NJRV3Bat3MHkJ8sXogGJrSzDql

Addis Standard

@addisstandardeng · Post #21661 · 10.03.2026 г., 06:20

#AU warns Gulf attacks threaten global energy and #African economies The African Union Commission (#AUC) has warned about escalating attacks on critical infrastructure in the #Persian_Gulf, cautioning that the incidents threaten global energy security and are already affecting African economies. The situation in the Gulf has worsened over the past week amid the ongoing #US-#Israeli war against #Iran, which has expanded into a broader regional conflict. In retaliation, Iran has targeted US military bases and critical infrastructure across several Gulf states. The strikes have heightened tensions and raised concerns about the stability of energy supplies and trade routes that are vital to the global economy. In a statement issued on Monday, AUC Chairperson Mahmoud Ali Youssouf highlighted the growing risks to trade and transportation in the region, noting that disruptions in ...... https://eastleighvoice.co.ke/middle-east/309166/auc-warns-gulf-attacks-threaten-global-energy-and-african-economies