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

Резултати

Пронајдени 17 слични објави

Пребарај: #policartoon

当前筛选 #policartoon清除筛选
Social Justice Watch

@social_justice_watch · Post #17658 · 18.10.2022 г., 17:20

Nobody Back Then Knew Slavery Was Wrong Transcript and description of cartoon: link A #PoliCartoon by me and @hawkins_becky, who did an awesome job with historic settings and costumes! Help us make cartoons at patreon.com/barry. Or by retweeting! :-) source

Hashtags

Social Justice Watch

@social_justice_watch · Post #17657 · 18.10.2022 г., 17:19

What We Can Afford A #PoliCartoon by @kevinwmoore and I! Transcript: link Read more (and moore) cartoons!: link You can support these cartoons with retweets or at patreon.com/barry! source

Hashtags

Social Justice Watch

@social_justice_watch · Post #17656 · 18.10.2022 г., 17:18

Just because you're rich white and privileged and you have an super-elite job and you haven't been fired doesn't mean you can't claim quit and claim victimhood! Transcript of #PoliCartoon: link Support by retweeting! Or directly at patreon.com/barry. source

Hashtags

Social Justice Watch

@social_justice_watch · Post #17655 · 18.10.2022 г., 17:17

Civil Forfeiture! A #PoliCartoon by me and @kevinwmoore! A topic that no one has been asking for a cartoon about! Read more toons! link Support more toons! patreon.com/barrysource

Hashtags

Social Justice Watch

@social_justice_watch · Post #17650 · 18.10.2022 г., 17:13

A Brief Taxonomy of Pro-Lifers Transcript of #PoliCartoon: link Help us make more cartoons at patreon.com/barry. :-) Read lots more cartoons here! linksource

Hashtags

Social Justice Watch

@social_justice_watch · Post #17645 · 18.10.2022 г., 04:07

There's Never Been A Worse Time For Free Speech! A #policartoon by me and @hawkins_becky. Transcript: link Help us make more by retweeting, or at patreon.com/barry. A $1 pledge really helps! Lots more toons to read! linksource

Hashtags

Social Justice Watch

@social_justice_watch · Post #17642 · 18.10.2022 г., 04:00

The Secret Home Lives of Teachers A #PoliCartoon by me and @hawkins_becky. Transcript: link Lots more cartoons to read here: link Help us make more! patreon.com/barrysource

Hashtags

12
ПретходнаСтраница 1 од 2Следна