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

Пребарај: #solidaritywithpalestine

当前筛选 #solidaritywithpalestine清除筛选
Freedom Flotilla Coalition

@FFC_official_channel · Post #595 · 16.07.2025 г., 11:46

Robert Martin is sailing to Gaza aboard the ‘Handala’. He reminds us that breaking Israel’s illegal siege on Gaza is the most important and urgent act that needs to be undertaken today. For Robert, joining the flotilla is a statement to the Palestinian people that they have not been forgotten as they endure a genocide while under brutal occupation - in spite of the consenting and complicit silence of the media and political establishments. For Robert, joining the flotilla is also a testament to posterity, and to future generations, that there were people who chose to act. “The world has woken up. Things are changing and I cannot wait for the day that there is a free Palestine.” Keep ‘Handala’ safe. End Israel’s Siege. #FreedomFlotilla#BreakIsraelsSiege#BreakTheSiege#SailToGaza#WomenAgainstBlockade#Handala#SolidarityWithPalestine

Freedom Flotilla Coalition

@FFC_official_channel · Post #584 · 12.07.2025 г., 11:11

At 70 years old, Vigdis Bjorvand from Norway is sailing to Gaza aboard 'Handala' to help break Israel's illegal siege - a journey she's been waiting for for years. A Palestine activist since 1978, Vigdis says she never wants her grandchild to say, “Grandma, you didn’t do anything.” She first joined 'Handala' in 2023, which did not manage to sail to Gaza, and tried again with 'Conscience' earlier this year. Now, she’s back on board, determined to deliver aid, medicine and solidarity to Palestinians in Gaza. As governments remain silent, Vigdis stands with the Palestinian people. Keep Vigdis safe. Keep 'Handala' safe. And help end Israel's illegal siege and genocide of Gaza. #FreedomFlotilla#BreakIsraelsSiege#BreakTheSiege#SailToGaza#WomenAgainstBlockade#Handala#SolidarityWithPalestine