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

Резултати

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

Пребарај: #sayyestowasteless

当前筛选 #sayyestowasteless清除筛选
NEA Singapore

@NEASingapore · Post #855 · 07.07.2024 г., 01:02

🚩 Red flag alert 🚩 Say “No” to single-use plastics! Embrace reusable alternatives instead. Every action counts towards a greener future! #SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #717 · 10.12.2023 г., 01:02

Looking forward to festive feasting? Here’s how you can feast ✨smart✨: Order only what you can finish and enjoy the satisfaction of a clean plate and choices well-made 🍴 #SayYesToWasteLess

NEA Singapore

@NEASingapore · Post #312 · 30.01.2022 г., 02:30

Order or cook just enough for you and your guests, to avoid wasting food this Lunar New Year. Let’s also observe safe management measures, to keep ourselves and our loved ones safe. #SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #1169 · 15.11.2025 г., 01:03

🎶 Ooooo~ This is an S.O.S.! 🎶 Good deals may be tempting but just because it’s on discount doesn’t mean you have to buy it. Reduce food wastage during the upcoming year-end festivities: ✅ Plan your meals and prep a shopping list ✅ Order only what you can finish ✅ Transform leftovers into new dishes #SayYEStoWasteLess#SustainableSG

NEA Singapore

@NEASingapore · Post #723 · 16.12.2023 г., 01:00

As the festive clock ticks, let's not forget the ticking dates in our pantry! Place items nearing their expiry dates at the front of your shelves. This helps you remember to use them soon and reduce food wastage. #SayYEStoWasteLess#TowardsZeroWaste

NEA Singapore

@NEASingapore · Post #501 · 04.02.2023 г., 02:01

Have leftover items from your Lunar New Year festivities? Be sure to place food that is near expiry within view, and practise the “First to Expire, First Out” approach when organising your home pantry! #SayYEStoWasteLess#TowardsZeroWaste

NEA Singapore

@NEASingapore · Post #499 · 28.01.2023 г., 02:01

A scrumptious meal with your family and friends doesn’t have to be excessive. If they are visiting other places beforehand, check with them first on how much they can eat. Let’s cook or order only what we can finish, to avoid food waste! #TowardsZeroWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #496 · 24.01.2023 г., 01:30

If you have extra steamboat ingredients from Lunar New Year gatherings, store these leftovers properly to keep them fresh for a longer time and avoid food wastage! More tips at www.nea.gov.sg/food-waste-management-strategies #TowardsZeroWaste#SayYEStoWasteLess

NEA Singapore

@NEASingapore · Post #447 · 22.10.2022 г., 01:30

Collecting more candy than we can finish this Halloween is less of a treat and more like a trick that leads to food waste! Say no to excessive candy, just like how you should only order and cook what you can eat. #SayYEStoWasteLess#TowardsZeroWaste

123•••56
ПретходнаСтраница 1 од 6Следна