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

Пребарај: #meetings

当前筛选 #meetings清除筛选

[The Embassy of South Africa in Moscow informs:] South African Ambassador to the Russian Federation, HE Mzuvukile Maqetuka received a delegation from the National Library of South Africa (NLSA) led by its CEO, Mr. Kepi Madumo (Left) and the Chairperson of NLSA, Mr. Andries Smith this owning, 12 December 2024 at the South African embassy. The South African delegation attended a two-day Conference of BRICS Libraries in Moscow. The delegation briefed the embassy staff on key issues pertaining to the organisation and collaboration amongst BRICS countries. #news#meetings

Сотрудники офиса Почётного консула ЮАР приняли участие в мероприятии «Дипломатический клуб КОНТЕКСТ». В мероприятии приняли участие Заместитель Руководителя Аппарата Губернатора Свердловской области и Правительства Свердловской области Вадим Дубичев, представители МИДа, иностранные дипломаты и почётные консулы. Политологи Екатеринбурга осветили актуальные вопросы российской внутриполитической повестки. #встречи ___________________ The Office of the Honorary Consul of South Africa participated in an event organized by the CONTEXT Diplomatic Club. The event was hosted by distinguished guests, including Vadim Dubichev, Deputy Chief of the Governor and Government of the Sverdlovsk Region’s Executive Office, Yekaterinburg-based political scientists, representatives from the Ministry of Foreign Affairs, as well as foreign diplomats and honorary consuls. During the event, Yekaterinburg political scientists led discussions on pressing issues within Russia's domestic political agenda. #meetings

Сотрудники офиса Почётного консула ЮАР приняли участие в мероприятии «Дипломатический клуб КОНТЕКСТ». В мероприятии приняли участие Заместитель Руководителя Аппарата Губернатора Свердловской области и Правительства Свердловской области Вадим Дубичев, представители МИДа, иностранные дипломаты и почётные консулы. Политологи Екатеринбурга осветили актуальные вопросы российской внутриполитической повестки. #встречи ___________________ The Office of the Honorary Consul of South Africa participated in an event organized by the CONTEXT Diplomatic Club. The event was attended by distinguished guests, including Vadim Dubichev, Deputy Chief of the Governor and Government of the Sverdlovsk Region’s Executive Office, Yekaterinburg-based political scientists, representatives from the Ministry of Foreign Affairs, as well as foreign diplomats and honorary consuls. During the event, Yekaterinburg political scientists led discussions on pressing issues within Russia's domestic political agenda. #meetings

Во вторник 10 декабря Почётный консул Сергей Мазуркевич встретился в Москве с Послом ЮАР Мзувукиле Макетукой. Они обсудили текущие проекты офиса Почётного консула ЮАР и планы на 2025 год. #встречи#новости#Посол#Макетука#Мазуркевич _________________ On Tuesday, December 10, Honorary Consul Sergey Mazurkevich met with South African Ambassador Mzuvukile Maqetuka in Moscow. They discussed current projects of the Honorary Consul's office and plans for 2025. #meetings#news#Ambassador#Maqetuka#Mazurkevich

Сотрудники офиса Почётного консула ЮАР приняли участие в мероприятии «Дипломатический клуб КОНТЕКСТ». 🌍 В числе участников — Заместитель Руководителя Аппарата Губернатора Свердловской области и Правительства Свердловской области Вадим Дубичев, иностранные дипломаты и почётные консулы. 🗣 Политологи Екатеринбурга осветили актуальные вопросы российской внутриполитической повестки. #Дипломатия#ЮАР#Екатеринбург#МеждународныеОтношения#Консул#Встречи#Политика#Контекст ___________________ The Office of the Honorary Consul of South Africa participated in an event hosted by the CONTEXT Diplomatic Club. 🌍 The event featured prominent guests, including Vadim Dubichev, Deputy Chief of Staff of the Sverdlovsk Region Government, foreign diplomats, and honorary consuls. 🗣 Yekaterinburg political scientists discussed current issues on Russia's domestic political agenda. #Diplomacy#SouthAfrica#Yekaterinburg#InternationalRelations#HonoraryConsul#Meetings#Politics#Context