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

Пребарај: #contact

当前筛选 #contact清除筛选

😄Contact ➖➖➖➖➖➖ 🔘Contact is a verb and means 'speak or write to someone' - often when someone wants to give or receive information. 🔜The doctor contacted me this morning to tell me the results of my tests. 🔜Please don't contact me with any more offers. 🔘Contact can also be used as a noun to talk about speaking or writing to someone. 🔘In contact with means 'speak or meet regularly'. 🔘Make contact means 'try to speak or write to someone after finding where someone is'. 🔘Lose contact means 'no longer communicate'. 🔜Stay in contact when you go away. 🔜After he left the city, I lost contact with him, but I'll try to make contact again if I find out his new address. 🔘Contact refers to a person who can help or give you information in work or socially. 🔜I have a contact at the company. Her name is Debbie. 🔜My contacts told me there's a job opening at the business. 🔘Contact as a noun refers to people whose names, numbers, and/or email addresses you have stored on your mobile phone. The list on your phone where you find this information is called contacts. 🔜I'll add you as a new contact on my phone. 🔜Look in my contacts. My brother's number is there. #Contact👨‍🏫@America ➖➖➖➖➖➖➖➖➖➖➖➖ 🆕 Crypto News @Money 😁 Crypto Game @Egame 🇺🇸 US News @America 🇯🇵 Japan News @Japan 🇦🇪 UAE News @Dubai ▶️ Popular Movies @Videos 😜 Best Funny Video @Funnys

Hashtags

dopingpong

@dopingram · Post #3162 · 03.08.2024 г., 06:58

«Лёгкий контакт», digital art, Doping Pong, 2001 Этот образ без преувеличения можно назвать классикой российского цифрового искусства. Предлагаем проследить преображение и эволюционные изменения, которые применили Doping Pong к этому сюжету на разных этапах творчества – от digital art до академической живописи. Легкий контакт - digital art, 2001 Легкий контакт (новая версия), digital art, 2005 Легкий контакт, бумага, пастель, 2015 год Легкий контакт, холст, акрил, 2018 год #dopingpong#ufo#space#love#alien#kiss#digitalart#russianart#light#contact