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

Резултати

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

Пребарај: #inspirational

当前筛选 #inspirational清除筛选
₿usiness Tips | Thoughts 💡

@quotesofzday · Post #269 · 07.08.2022 г., 12:01

Remember, Most of your stress comes from the way you respond, not the way life is. Adjust your attitude. Change how you see things. Look for the good in all situations. Take the lesson and find new opportunities to grow. Let all the extra stress, worrying, and overthinking go. #Inspirational

₿usiness Tips | Thoughts 💡

@quotesofzday · Post #268 · 07.08.2022 г., 11:59

Prioritize your mental and spiritual wellness. Do things that make you happy. Take time to nurture yourself. Don’t rush the process. Don’t judge where you’re at or where you think you should be. Just be kind and patient with yourself. Things are unfolding for you. #Inspirational

₿usiness Tips | Thoughts 💡

@quotesofzday · Post #258 · 05.08.2022 г., 16:01

Wrinkles, scars, imperfections, strengths, & weaknesses - all these made you who you are today - a strong, independent, beautiful human being. Embrace it all with gratitude. When you learn to accept & love everything about you, nobody can ever use it against you. #Inspirational

Quiet World 🍁

@QuietWorld · Post #7360 · 08.06.2020 г., 03:15

“𝕋𝕠 𝕤𝕦𝕔𝕔𝕖𝕖𝕕, 𝕪𝕠𝕦 𝕨𝕒𝕟𝕥 𝕥𝕠 𝕓𝕖 𝕒𝕓𝕝𝕖 𝕥𝕠 𝕣𝕖𝕘𝕦𝕝𝕒𝕥𝕖 𝕪𝕠𝕦𝕣 𝕚𝕞𝕡𝕦𝕝𝕤𝕖𝕤 𝕨𝕙𝕚𝕝𝕖 𝕒𝕝𝕤𝕠 𝕙𝕒𝕧𝕚𝕟𝕘 𝕥𝕙𝕖 𝕚𝕞𝕒𝕘𝕚𝕟𝕒𝕥𝕚𝕠𝕟 𝕥𝕠 𝕤𝕖𝕖 𝕨𝕙𝕒𝕥 𝕥𝕙𝕖 𝕗𝕦𝕥𝕦𝕣𝕖 𝕨𝕚𝕝𝕝 𝕓𝕖 𝕝𝕚𝕜𝕖 𝕚𝕗 𝕪𝕠𝕦 𝕥𝕣𝕪 𝕤𝕠𝕞𝕖𝕥𝕙𝕚𝕟𝕘 𝕟𝕖𝕨.” #selfreminder#motivation#inspirational#life#wisdom#success @quietworld🍃