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

Резултати

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

Пребарај: #butterflies

当前筛选 #butterflies清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #1129 · 14.12.2025 г., 18:11

🌎 Spectacular animal migrations include the annual journey of monarch butterflies, which travel up to 4,800 kilometers from Canada and the U.S. to central Mexico. These butterflies navigate using a combination of environmental cues and an internal sun compass in their antennae. ✨ #migration⚡#butterflies⚡#nature 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1388 · 29.04.2026 г., 12:11

🌎 Monarch butterflies complete a multigenerational migration from Canada to central Mexico, traveling up to 4,500 kilometers. No single butterfly makes the entire round trip; several generations are born and die along the way. ✨ #butterflies⚡#migration⚡#insects 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1282 · 08.02.2026 г., 22:11

🌎 Each year, monarch butterflies migrate up to 4,800 kilometers from Canada and the northern United States to overwinter in central Mexico. Clusters of millions gather on oyamel fir trees, using environmental cues like the angle of sunlight to navigate. ✨ #migration⚡#butterflies⚡#insects 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #756 · 15.09.2025 г., 18:22

🌎 Monarch butterflies in North America complete one of the longest insect migrations, traveling up to 4,800 kilometers from Canada and the U.S. to central Mexico. Each fall, millions gather in mountain forests, forming dense colonies that help them survive winter’s cold. ✨ #butterflies⚡#migration⚡#insects 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #549 · 12.08.2025 г., 20:22

🌎 Some butterflies taste with their feet! Tiny sensors on their legs let them “sample” leaves, ensuring they lay eggs only on the best plants for their caterpillars. ✨ #butterflies⚡#senses⚡#nature 👉subscribe Interesting Planet

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