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

Резултати

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

Пребарај: #byob

当前筛选 #byob清除筛选
I-DLE* UPDATE (SLOW)

@gidle_update · Post #45677 · 16.09.2025 г., 11:06

250913 || JohnMaat 𝕏 UPDATE BYOB phone wallpaper selfie📸 Chef Yuqi appears just for Neverland👨‍🍳 🦒🐶 : Ta-da! I made something Neverland likes✨ 🔗Go watch BYOB Idle Yuqi episode: https://youtu.be/M8TveLXOkHg #BYOB#Idle#idle#Yuqi#YUQI –🦋 ── @GIDLE_UPDATE ──

NEA Singapore

@NEASingapore · Post #696 · 31.10.2023 г., 01:01

This Halloween, make your carbon footprint less scary! 🍿 Having a spooky movie night? Bring along reusable popcorn containers and cups. 👻 Hitting a few haunted houses? Don't forget to keep hydrated with a reusable bottle. 🍭 And if you’re thinking of hitting the sweet shops, keep a reusable bag handy. #SustainableSG#BYO#BYOB

NEA Singapore

@NEASingapore · Post #669 · 13.10.2023 г., 01:02

Bring your reusable bag when you go shopping! Every action counts when it comes to saving planet Earth, and a little goes a long way when it comes to savings 💰 Show the Earth and your wallet some love! #SayYEStoWasteLess#BYO#BYOB

NEA Singapore

@NEASingapore · Post #648 · 23.09.2023 г., 01:01

Lock screen reminders are the new sticky notes. So set a trendy reminder to bring your own reusable bag before heading out! Let’s save the planet, one bag at a time 🛍#BYO#BYOB#SayYEStoWasteLess

gov.sg

@Govsg · Post #1755 · 12.07.2023 г., 08:42

Level up your eco-game! ♻️💪 Tote-ally rockin’ a reusable bag = Saving money, slashing trash and giving our environment a healthy splash! 🌿🌏 #BYOB#ZeroWasteNation#Sustainability#SayYEStoWasteLess For more news and updates on government announcements, follow us on WhatsApp Channels at go.gov.sg/wa-channels!😊

I-DLE* UPDATE (SLOW)

@gidle_update · Post #45662 · 16.09.2025 г., 11:06

250911 || JohnMaat 𝕏 UPDATE BYOB Season 3 Final Chef👨‍🍳 ˗ˋˏ YUQI i-dle ˎˊ˗ Yuqi (in charge of all things 𝒮𝐸𝒳𝒴 ⒸⓊⓉⒺ for IDLE) Would you like to watch the BYOB Wave Show? > Gi > Ginio 🔥15 episodes will be released tomorrow at 10 AM (KST) 🔗http://youtube.com/@John_maat #BYOB#박준형#브라이언 #아이들#idle#우기#YUQI –🦋 ── @GIDLE_UPDATE ──

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