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

Пребарај: #electricalgrid

当前筛选 #electricalgrid清除筛选
Venezuelanalysis

@venanalysis · Post #1732 · 30.08.2024 г., 12:20

[BREAKING] Venezuela is facing a nationwide blackout, with all 24 states affected since early this morning. Authorities are working to restore power, and buses have been deployed in Caracas as the subway system is down. Story developing. Full report here: https://shorturl.at/omBak #ElectricalGrid

Venezuelanalysis

@venanalysis · Post #2314 · 24.03.2026 г., 20:45

📰 NEWS | Venezuela: Rodríguez Announces Electricity Rationing Ahead of Heatwave, Drought Forecast Venezuela has introduced a 45-day electricity saving plan as authorities anticipate increased demand driven by extreme heat and drought conditions, according to Acting President Delcy Rodríguez. The government also confirmed plans to reform the electricity sector to allow private investment through joint ventures in generation and distribution, aiming to address long-standing infrastructure limitations. Recent outages and limited operational capacity, estimated at 12–14 GW out of 34 GW installed, highlight ongoing challenges in the national grid. Read the full report here 👉🏾https://shorturl.at/2SmsF #ElectricalGrid#Sanctions

Venezuelanalysis

@venanalysis · Post #1761 · 30.09.2024 г., 21:22

VA columnist Jessica Dos Santos describes a recent nationwide blackout in Venezuela and the memories from similar events in 2019. While the country returned to normal faster this time, questions about the state of the electrical infrastructure linger. Read the full column here 👉🏼https://shorturl.at/kFJlK #ElectricalGrid#TalesofResistance

Venezuelanalysis

@venanalysis · Post #1919 · 25.03.2025 г., 23:32

📰 NEWS | Venezuelan Gov’t Scales Down Public Sector Schedule in Electricity Rationing Measure The Venezuelan government has announced a six-week electricity rationing plan for state institutions, citing a climate emergency. Public offices will operate on alternating days with reduced hours (8 am-12:30 pm). Essential services remain unaffected. Western states, including Mérida, Táchira, Barinas, and Zulia, have faced daily blackouts of up to eight hours. Analysts point to drought-related hydroelectric challenges and concerns over the country’s transmission infrastructure. 🔗 Read the report here: https://venezuelanalysis.com/news/venezuelan-govt-scales-down-public-sector-schedule-in-electricity-rationing-measure/ #ElectricalGrid#PublicSector