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

Пребарај: #dedipath

当前筛选 #dedipath清除筛选
VPS简测

@vps_test · Post #479 · 31.08.2023 г., 10:31

JJNEWS DediPath将要跑路(没提到洛杉矶区域,暂不清楚是否会全部跑) Dear mjj, We will are writing to you regarding your service at DediPath. With a heavy heart we must announce that DediPath will be discontinuing operations effective 8/31/23. Please migrate your data and take backups as soon as possible. In regards to our colocation customers if you are in the following locations please send a ticket to [email protected] for equipment removal: Dallas Las Vegas Denver Atlanta Jacksonville In regards to our colocation customers if you are in the following location please send a ticket to [email protected] for equipment removal: Seattle In regards to our colocation customers if you are in the following locations please send a ticket to [email protected] for equipment removal: Phoenix In regards to our colocation customers if you are in the following locations please send a ticket to [email protected] for equipment removal: Secaucus Redondo Beach San Jose If you have a domain registered with us please transfer it out ASAP. We are truly sorry for the inconvenience this has caused. We appreciate your business and support over the years and this is heart breaking to everyone at DediPath. Sincerely, DediPath #jjnews#dedipath

VPS简测

@vps_test · Post #131 · 07.06.2023 г., 02:58

DediPath Hybrid Server(高性能不超售服务器)原价11.4刀,官方5折->5.7刀 2C4G250G HDD 意外的是流媒体解锁,G口真不限流量!适合建站,中国移动部分省份用不了(比如江苏) #dedipath#1Gbps#不限流量#流媒体解锁