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 слични објави

Пребарај: #investnow

当前筛选 #investnow清除筛选
Crypto Fight || News 🚀

@cryptofightnews · Post #1937 · 08.08.2024 г., 05:37

🚀 Huge News for $BCCOIN! 🚀 Big things are coming for $BCCOIN! ⭐️ Upcoming Developments: - Within 7 days: Listing on a top-tier exchange! - 7 days: Announcing a groundbreaking bank partnership! - 4 weeks: Adding $6M liquidity to DEXs and conducting major token burns! Why Invest Now? With the current market conditions, NOW is the perfect time to invest in $BCCOIN! Don't miss out on this incredible opportunity! 📊 Buy $BCCOIN Here: - Gate.io: gate.io/trade/BCCOIN_USDT - Bitget: bitget.com/price/blackcardcoin - MEXC: mexc.com/price/BCCOIN - BingX: bingx.com/spot/BCCOINUSDT - Bitmart: bitmart.com/trade/en-US #BCCOIN#CryptoNews#InvestNow#CryptoRevolution@BlackCardCoin --- 🚀 Huge News for $BCCOIN! 🚀 Big things are coming for $BCCOIN! ⭐️ Upcoming Developments: - Within 7 days: Listing on a top-tier exchange! - 7 days: Announcing a groundbreaking bank partnership! - 4 weeks: Adding $6M liquidity to DEXs and conducting major token burns! Why Invest Now? With the current market conditions, NOW is the perfect time to invest in $BCCOIN! Don't miss out on this incredible opportunity! 📊 Buy $BCCOIN Here: - Gate.io: gate.io/trade/BCCOIN_USDT - Bitget: bitget.com/price/blackcardcoin - MEXC: mexc.com/price/BCCOIN - BingX: bingx.com/spot/BCCOINUSDT - Bitmart: bitmart.com/trade/en-US?symbol=BCCOIN_USDT Stay Updated: - Telegram: t.me/Official_BcCoin - Twitter: twitter.com/BlackCardCoin - Website: blackcardcoin.com Key Resources: - Tokenomics: download.blackcardcoin.com/BCCoin_BlackCardCoin_Tokenomics_v2.pdf - Roadmap: download.blackcardcoin.com/BCCoin_BlackCardCoin_Roadmap_v2.pdf - Whitepaper: download.blackcardcoin.com/BCCoin_BlackCardCoin_Whitepaper_v2.pdf ### Expert Opinions: - CryptoGuru: "$BCCOIN is poised to hit new all-time highs with these strategic moves. Don't miss out on this incredible opportunity!" - BlockchainMaven: "With the upcoming listings and partnerships, $BCCOIN is set to become a dominant player in the crypto space." ⭐️ Don't wait until it's too late—secure your future with $BCCOIN now! ⭐️

⚡️𝗣𝗮𝗿𝘁𝗻𝗲𝗿𝘀𝗵𝗶𝗽 𝗔𝗻𝗻𝗼𝘂𝗻𝗰𝗲𝗺𝗲𝗻𝘁 ⚡️ ᶜʳʸᵖᵗᵒ ¹⁰⁰ˣ ⱽ ᴹᵃʳˢᵒ ᵒⁿ ᴱᵀᴴ ⁽ ᴮᵃˢᵉ ⁾🔹 Marso Token: The Next BIG Thing in Crypto is Here! 🔥🔥🔥 🚀 The new BIG thing in the crypto market is here: Marso Token is launching, and it’s coming in HOT! Ready to soar, Marso Token is set to redefine possibilities in the crypto universe. 🫡🫡🫡 Join our journey, follow all our socials, stay tuned for the latest updates, and don’t miss your chance to invest early! ⭐️⭐️⭐️⭐️⭐️ 🤑🤑🤑 Get in on the action now—exclusively on BitMart! Let’s make history together with Marso Token. 🥰🥰🥰 🤩🤩🤩🤩 Join the Marso community for exciting news, contests, and more. This is only the beginning, and you’re invited to be part of it. 🤟🤟🤟 ✅Website: marso.tech ✅Telegram: https://t.me/MarsoUniverseCommunity 🚀X: https://x.com/marsouniverse?s=21 📱Instagram: https://www.instagram.com/marsouniverse?igsh=ZjR4cW5vZXVpdmMy&utm_source=qr #MarsoToken#CryptoLaunch#BiggestCrypto#InvestNow#CryptoCommunity#Bitmart#MarsoUniverse#AltcoinSeason#CryptoFuture#BlockchainInnovation#EarlyInvestors#CryptoBuzz#NextBigCoin#FutureOfFinance#MarsoToTheMoon