@profile_pictures_tm · Post #19211 · 04.02.2025 г., 14:02
#Animations🦋 💜
Hashtags
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
Пребарај: #animations
@profile_pictures_tm · Post #19211 · 04.02.2025 г., 14:02
#Animations🦋 💜
Hashtags
@profile_pictures_tm · Post #14940 · 20.06.2023 г., 11:00
#Animations💜💪👑
Hashtags
@profile_pictures_tm · Post #13030 · 26.01.2023 г., 10:55
#Animations
Hashtags
@profile_pictures_tm · Post #12921 · 18.01.2023 г., 18:10
#Animations ᴘʀᴏғɪʟᴇ ᴘɪᴄᴛᴜʀᴇs sᴇᴄᴏɴᴅ ᴄʜᴀɴɴᴇʟ🔻 ᴄʀʏᴘᴛᴏ ɴᴇᴡs📈
Hashtags
@profile_pictures_tm · Post #12255 · 29.11.2022 г., 09:24
#Animations
Hashtags
@profile_pictures_tm · Post #12073 · 19.11.2022 г., 10:30
#Animations
Hashtags
@profile_pictures_tm · Post #11565 · 18.10.2022 г., 09:57
#Animations
Hashtags
@profile_pictures_tm · Post #10733 · 08.09.2022 г., 06:14
#Animations
Hashtags
@profile_pictures_tm · Post #10033 · 08.08.2022 г., 10:55
#Animations
Hashtags
@profile_pictures_tm · Post #9616 · 18.07.2022 г., 12:55
#Animations
Hashtags
@profile_pictures_tm · Post #9296 · 03.07.2022 г., 11:42
#Animations
Hashtags
@profile_pictures_tm · Post #6825 · 08.02.2022 г., 09:09
#Animations
Hashtags