@LiveHealthy · Post #6897 · 26.12.2024 г., 22:37
#healthy
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
Пребарај: #healthy
@LiveHealthy · Post #6897 · 26.12.2024 г., 22:37
#healthy
Hashtags
@ncdcgov · Post #4443 · 05.03.2025 г., 13:36
#Measles infection can lead to complications, especially in young children & those with weakened immune systems. Ensure the completion of routine immunisation for your children or wards to keep them safe and #healthy. #TakeResponsibility
@ncdcgov · Post #4154 · 09.01.2024 г., 08:32
#Measles infection can lead to complications, especially in young children & those with weakened immune systems. Ensure the completion of routine immunisation for your children or wards to keep them safe and #healthy. #TakeResponsibility
@ncdcgov · Post #4112 · 04.12.2023 г., 12:29
Unvaccinated young children are at the highest risk of #measles infection and its complications. Ensure the completion of routine immunisation for your children or wards to keep them safe and #healthy. #TakeResponsibility
@ncdcgov · Post #3677 · 05.01.2023 г., 11:58
Unvaccinated young children are at the highest risk of #measles infection and its complications. Ensure the completion of routine immunisation for your children or wards to keep them safe and #healthy. #TakeResponsibility
@ncdcgov · Post #3789 · 31.03.2023 г., 08:52
Vaccination is the best prevention measure against #CerebrospinalMeningitis. Ensure you complete the routine immunisation for your children or wards to keep them safe and #healthy. #TakeResponsibility
@ncdcgov · Post #4336 · 22.07.2024 г., 09:39
Vaccination is the best prevention measure against #CerebrospinalMeningitis. Ensure you complete Nigeria's routine immunisation schedule for your children or wards to keep them safe and #healthy. #DefeatMeningitis
@dzdigital3 · Post #18992 · 11.09.2025 г., 13:16
Détails and Price 👇 https://s.click.aliexpress.com/e/_EH5wZa6 Adjust Back Stretcher For Back Spine Lumbar Support Massage Muscle Relax Stretcher Posture Therapy Corrector Airbag Level High #neck#massager#healthy#healthylifestyle#massagetherapist
@dzdigital3 · Post #18991 · 11.09.2025 г., 13:11
Détails and Price 👇 https://s.click.aliexpress.com/e/_EHHIpge Portable Neck Massager for Neck Pain, Intelligent Portable Neck Massager with Heat Function, USB Charging Neck Relax Massager #neck#massager#healthy#healthylifestyle#massagetherapist
@yuristipravda · Post #753 · 24.03.2026 г., 07:04
Ну что, с коровами почти покончили, возьмёмся за пчёл: Лабораторно выращенные медоносные пчелы, созданные лишь для того, чтобы быть рабами и умирать рано. Генеральный директор 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