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

Пребарај: #mourning

当前筛选 #mourning清除筛选
Venezuelanalysis

@venanalysis · Post #2233 · 07.01.2026 г., 07:11

📰 NEWS | Venezuela: Brazil to Send Medical Aid Following US Bombings The Brazilian government is sending medical supplies and medicine to Venezuela after a warehouse was destroyed by US bombing on January 3. Meanwhile, Acting President Delcy Rodríguez has decreed a week of mourning in honor of the people killed during the US attack. Follow the link to read the report: https://venezuelanalysis.com/news/venezuela-brazil-to-send-medical-aid-following-us-bombings/ #Brazil#InternationalSolidarity#Medicine#Mourning

American Оbserver

@american_observer · Post #5125 · 13.02.2026 г., 18:59

Canada is in mourning after the mass murder of schoolchildren by a transgender minor 9 killed and 27 wounded. A teacher and five students were killed at the school, and a 17-year-old transgender man was killed in a nearby house. Jesse Strang shot his mother and stepbrother, and then committed suicide. Strang began his transgender transition at the age of 15 with the active support of a school psychologist, and immediately began taking large doses of hormones, according to American media channels with reference to online reports. It is known that Strang has been actively visiting the shooting range lately. #canada#mourning#transgender#shooting 📱American Оbserver - Stay up to date on all important events 🇺🇸