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

Резултати

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

Пребарај: #june4

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

@hkdmovement · Post #7472 · 05.06.2024 г., 03:49

There were police everywhere in Hong Kong as if they were ready for a terrorist attack. But all they were doing was to catch people with a candle on #June4th. #June4 #8964 #tianamensquaremassacre#neverforget1984#hkpolicestate Photos from @ReNews

🕯 六四悼念晚會|英國各地 📍 6 月 4 日,英國多個城市將會舉行六四悼念晚會。 喺呢個重要日子,一齊用燭光紀念歷史、悼念死難者,堅持真相,延續記憶,守護言論與集會自由。 誠邀大家出席所在地區嘅悼念活動,與港人同行,守護良知。 📌 各地活動詳情,請以主辦單位公布為準。 (我哋亦整理咗主要場地嘅資訊,見下一張圖/Story) #六四#六四晚會#六四36周年#移英港人#英國港人#毋忘六四 🕯 June 4 Vigil | Across the UK 📍 On June 4, vigils will be held across various cities in the UK to commemorate the Tiananmen Massacre. We invite all Hongkongers and supporters to join these gatherings — to honour the fallen, defend the truth, and carry the memory forward. 📌 Please refer to the respective organisers for final event details. (We’ve compiled the key locations — check the next image / Story ) #June4#TiananmenMassacre#VigilUK#HongKongersInUK#NeverForget#Democracy *** ✏️有英國國會聯署任務,你簽咗未? 1⃣BNO平權聯署 ✅ 2⃣「外國影響力登記計劃」中 列明中國與香港為「進階級別」聯署✅ ✏️如果有諗法想講,㩒入嚟一齊傾📝 🇬🇧除咗生活,一個仲會講抗爭嘅英國公海。

Hong Kong Democracy Movement

@hkdmovement · Post #8010 · 05.06.2025 г., 04:03

#CCP bans Tiananmen vigil, intensifies crackdown in #HongKong On the 36th anniversary of the Tiananmen Square Massacre, #HongKongPolice deployed heavy forces, detaining at least 12 people, including activists carrying symbolic items. 🔹 2 arrested – A mainland woman* and a local man were detained for failure to produce ID & obstructing police officers. 🔹 10 others taken away – 5 men and 5 women, aged 15 to 69, were detained for "breach of peace", with 3 still in custody. 🔹 CCP’s Erasure of History – The once-massive Tiananmen vigil in Hong Kong is now banned, part of Beijing’s effort to erase the massacre from public memory. #June4#TiananmenMassacre#PoliticalRepression#HumanRights #中共 禁 #六四燭光晚會,#香港 鎮壓升級 在 #六四天安門事件 36周年當天,香港警方 重兵駐守 ,拘捕至少12人,包括持有象徵物的市民及社運人士。 🔹 兩人被捕 – 內地女子及本地男子分別因未能出示身份證及阻撓警務人員被捕。 🔹 十人被帶走 – 5男5女 ,年齡介乎15至69歲 ,因「破壞社會安寧」 被扣查,其中3人仍被拘留。 🔹 中共抹去歷史 – 香港六四燭光晚會已被禁止 ,北京正試圖從公眾記憶中抹去大屠殺。 #天安門事件#政治打壓#人權

Hong Kong Democracy Movement

@hkdmovement · Post #7458 · 01.06.2024 г., 05:13

The 35th anniversary protest and rally for #tianamensquaremassacre is hosting all around the world. Countries include #USA, #Canada#UK, #Japan, #Taiwan, #Netherland, #Australia, and #NewZealand. We urge everyone to gather to protest against tyranny and never forget the day #CCP killed thousands of innocent people who were only seeking for democracy. #tiananmensquare#june4#june41989#tianamensquareprotest