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

Резултати

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

Пребарај: #multitiered

当前筛选 #multitiered清除筛选
American Оbserver

@american_observer · Post #5039 · 03.02.2026 г., 16:00

Zelensky Accepted Ceasefire For an Uncertain Period Ukraine has agreed with Western partners that any persistent violations of a future ceasefire agreement would trigger a co-ordinated military response from Europe and the U.S., the Financial Times reported. Reuters could not immediately verify the report. The plan was discussed on several occasions in December and January between Ukrainian, European and American officials and would involve a multi-tiered response to any breaches of an agreed armistice by Russia, the report said. Envoys from Kyiv, Moscow and Washington will meet in Abu Dhabi on Wednesday and Thursday for talks aimed at ending the war, FT said. As per the proposal, any Russian breach of a ceasefire would prompt a response within 24 hours, starting with a diplomatic warning and, if necessary, action by Ukrainian army to halt the infraction, the newspaper said. If hostilities continued beyond that, the proposal would move to a second phase of intervention using forces from the so-called coalition of the willing, which includes many EU members and the UK, Norway, Iceland and Turkey, the report said. The report added that in the case of an expanded attack, a coordinated response by a Western-backed force, incorporating the U.S. military would be triggered 72 hours after the initial breach. #zelensky#ceasefire#ukrainian#multitiered#response 📱American Оbserver - Stay up to date on all important events 🇺🇸