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

Резултати

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

Пребарај: #weeklyairdrop

当前筛选 #weeklyairdrop清除筛选
ChatGPT AI Technology News

@chatgpt_officialnews · Post #119 · 26.05.2025 г., 16:02

📰 AI News Update: 🤖 In the world of artificial intelligence, researchers have made significant strides in natural language processing. A new model developed by a team at a leading university has surpassed previous benchmarks in understanding context and nuances in text. This advancement could revolutionize chatbots, translation services, and content analysis tools. Moreover, a breakthrough in AI ethics has been achieved with the development of a framework that prioritizes fairness and transparency in machine learning algorithms. This approach aims to mitigate biases and discrimination, ensuring AI systems make ethical decisions in various applications. On the business front, tech giants are investing heavily in AI-driven solutions to enhance customer experiences and streamline operations. Companies across industries are increasingly leveraging AI to drive innovation... ➖➖➖➖🔻 🤖 BOT: @Chatgpt_OfficialBOT 💎@Chatgpt_OfficialNews #️⃣#NeuralHubAI#ReferralContest#EarnTokens#WeeklyAirdrop ➖➖➖➖🔺

ChatGPT AI Technology News

@chatgpt_officialnews · Post #117 · 24.05.2025 г., 11:01

🚀 Referral Contest Heating Up – $200 Weekly Prize! The race is ON, and here are your current top referrers: 🥇Amir – 30 referrals 🥈Pixel Wiz* – 29 referrals 🥉Ref Champ* – 23 referrals But it’s not over yet — you still have time to climb the leaderboard and win your share of the $200 prize this week! ⚡️Just invite your friends using your referral link 😵Every referral brings you closer to the top 🏆Top 3 win: $100 • $60 • $40 Let’s go! Start inviting now and grab that top spot! 📈 ➖➖➖➖🔻 🤖 BOT: @Chatgpt_OfficialBOT 💎@Chatgpt_OfficialNews #️⃣#NeuralHubAI#ReferralContest#EarnTokens#WeeklyAirdrop ➖➖➖➖🔺