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

Пребарај: #yuenlong721

当前筛选 #yuenlong721清除筛选
Hong Kong Democracy Movement

@hkdmovement · Post #7946 · 01.03.2025 г., 03:37

The sentencing of former legislator Lam Cheuk-ting and 6 others in the 7.21 Yuen Long incident has sparked international attention. Videos widely available online show Lam and others being attacked during the incident, raising questions about the interpretation of evidence in the trial. Many have expressed concerns that actions of self-defense and efforts to protect others were mischaracterized, leading to charges of rioting. Critics argue that the case reflects a broader effort to align the narrative with a predetermined scenario. This has drawn calls from international communities urging for transparency, justice, and the protection of fundamental human rights. #YuenLong721#RuleOfLaw#HumanRights 前立法會議員林卓廷與另外六人在7.21元朗事件中被判暴動罪,引發國際關注及爭議。網上廣泛流傳的影片顯示,林卓廷及其他人在事件中遭受襲擊,令外界對審訊中證據的解讀產生疑問。不少聲音質疑,自衛及保護他人的行為被曲解,最終導致暴動罪的指控。 有評論指出,此案件反映了更廣泛的企圖,將事件情節配合既定敘事。此案件引發國際社會對透明度、公正性及基本人權的呼籲。 #元朗721