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

Резултати

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

Пребарај: #pollination

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

@interesting_planet_facts · Post #1184 · 02.01.2026 г., 12:11

🌎 Leafcutter bees and flowering plants have a mutualistic relationship—bees gather pollen and nectar to feed their larvae, while plants get pollinated. Each bee can visit up to 100 flowers in a single foraging trip. ✨ #symbiosis⚡#animals⚡#pollination 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #417 · 25.07.2025 г., 17:22

🌎 A single honeybee visits up to 5,000 flowers in one day, gathering nectar to make honey and pollinate plants—crucial for global food crops! ✨ #bees⚡#pollination⚡#nature 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #540 · 11.08.2025 г., 13:22

🌎 The flying fox bat of Southeast Asia boasts a wingspan up to 1.7 meters. Unlike most bats, it feeds mainly on fruit and nectar, playing a key role in pollinating trees that support tropical forests and countless wildlife. ✨ #flyingfox⚡#pollination⚡#rainforest 👉subscribe Interesting Planet

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40257 · 05.12.2025 г., 15:00

California trucks 1.5 million to 2.6 million bee hives each spring to pollinate almond farms. Pesticides and fungicides used on almonds hurt bees’ health and make it hard for them to find food. Bees also get stressed from long trips and losing their honey. These problems cause many bees to die or disappear. Almonds are pasteurized, which lowers their natural quality. Reducing almond farming could help protect bees and the environment by making almonds rarer. 🐝🌰🚛🌱 [Read more] [Read more] @googlefactss #Bees#Almonds#Pollination#Pesticides#ColonyCollapseDisorder#SaveTheBees#Sustainability

Ну что, с коровами почти покончили, возьмёмся за пчёл: Лабораторно выращенные медоносные пчелы, созданные лишь для того, чтобы быть рабами и умирать рано. Генеральный директор ForgeBee Адам Гамильтон говорит, что компания использует ИИ и робототехнику для выращивания партий одноразовых пчел, которые будут отправляться пчеловодам и фермерам. Он говорит: "Их поведение будет манипулироваться с помощью комбинации химических веществ, которые по сути заставят пчел чаще собирать пыльцу". Эти "единицы", как они их называют, будут иметь срок жизни от двух до трех недель, посвященных опылению сельскохозяйственных культур. Кто-нибудь еще обеспокоен этим? А если эти измененные, лабораторно выращенные пчелы окажутся в дикой природе... что может пойти не так? Читайте: https://www.brownfieldagnews.com/news/lab-grown-honeybees-could-be-future-of-food-production/ #LabGrownHoneybees#honeybees#bees#pollinators#pollination#beekeepers#food#health#healthy#holistic#holistichealth#gmofreecanada#gmofreeusa#toxinfreeusa https://t.me/VseWeda/88080