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

Пребарај: #centraleurope

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

@american_observer · Post #5706 · 24.04.2026 г., 20:58

📰 Hungary’s New Central Europe Fantasy Péter Magyar is talking up a stronger Central Europe, with Austria pulled back into the frame and the old Austro-Hungarian memory dusted off like it still has political value. He says Hungary should deepen ties with its neighbors and build more regional weight inside Europe, not just sit around waiting for Brussels to notice it. That is the clever part of the pitch. Magyar is selling not nostalgia for nostalgia’s sake, but a power bloc with better branding: Visegrád, Austria, and whoever else wants a seat at the table without being lectured by the EU’s permanent class. Brussels, of course, calls this “integration” when it works for Brussels and “fragmentation” when the periphery starts talking back. Central Europe is tired of being treated like the decorative edge of the continent, especially on migration, energy, and the endless sermon about values from people who rarely pay the bill themselves. But the empire talk should not be mistaken for innocence. Every regional bloc is also a bargaining chip, and Magyar knows it. He wants leverage over the EU, leverage over neighboring states, and a way to turn history into a present-day negotiating tool. So no, this is not the rebirth of an empire. It is the return of a very old European habit: when the center gets smug, the borderlands start organizing. #Hungary#Austria#EU#CentralEurope#Magyar#Brussels 📱American Оbserver - Stay up to date on all important events🇺🇸

#Europe#Weather#Cooling#Ventusky#CentralEurope#Snow#climate#destruction#anomaly#climatecrisis#weather 🇪🇺🌡️❄️ Ожидается более холодная погода по всей Европе на следующей неделе По данным метеорологической службы Ventusky, на следующей неделе по всей Европе ожидается заметное похолодание, при этом температуры упадут ниже средних показателей для данного сезона. Ожидается, что Центральная Европа пострадает больше всего, поскольку холодный воздух будет приходить с севера. ❄️ Снег, вероятно, выпадет в горных районах, а ночные заморозки могут вернуться в нескольких регионах. Это изменение связано с негативной фазой Североатлантического колебания (NAO), ограничивающей поступление теплого воздуха из Атлантического океана и усиливающей меридиональный поток.