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

Резултати

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

Пребарај: #single

当前筛选 #single清除筛选
Андрей Лаупер

@free4ones · Post #545 · 29.08.2024 г., 06:24

📻 Годы работы в эфире музыкальных радиостанций не проходят бесследно - тяга к микрофону и к свежим реализам не исчезает😎 💿 Свежий летний попсовый сингл из чарта UK TOP 40: Fred again.. / Anderson .Paak / CHIKA - Places To Be Британцы в очередной раз удивляют своей прогрессивностью и технологичным продакшном. #single#summer

探索号

@seeker_rc · Post #19839 · 07.05.2026 г., 03:25

大家是怎么管理和检索 SingleFile 保存的网页的? 长期都是用 single file 保存网页,但发现自己想用的时候,却始终找不到自己保存,目前想到的解决方案是自动 rag 清洗检索,但总觉得这玩意儿之前应该有人做过了吧 via V2EX 分享创造 标签: #网页#SingleFile#single ⚡️探索号频道 ⚡️探索者频道 ⚡️探索者交流群 ⚡️ Youtube 频道:科技探索者 每天推荐有趣内容,欢迎订阅、转发。

djangoproject

@djangoproject · Post #107 · 02.08.2016 г., 15:22

https://github.com/python/asyncio The #asyncio#module provides infrastructure for writing #single-threaded concurrent code using #coroutines, #multiplexing#I/O access over sockets and other resources, running network clients and servers, and other related primitives. Here is a more detailed list of the package contents: a pluggable event loop with various system-specific implementations; transport and protocol abstractions (similar to those in Twisted); concrete support for TCP, UDP, SSL, subprocess pipes, delayed calls, and others (some may be system-dependent); a Future class that mimics the one in the concurrent.futures module, but adapted for use with the event loop; #coroutines and #tasks based on yield from (PEP 380), to help write concurrent code in a sequential fashion; cancellation support for Futures and coroutines; synchronization primitives for use between coroutines in a single thread, mimicking those in the #threading module; an interface for passing work off to a threadpool, for times when you absolutely, positively have to use a library that makes blocking I/O calls. Note: The implementation of asyncio was previously called "Tulip".

Desi Memes Funny Jokes

@DESI_MEMES_Funny_Jokes · Post #6008 · 10.12.2024 г., 12:03

. . . . . #crusheverything#crush#crushlovers#sendthistoyourcrush#crushmemes#crushrejection#crush😍#crushquote#love#lovecrush#singlelifeproblems#singlefriends#singleme#singlelifebelike#singlemen#singleboy#single#boyswillbeboys#boystory#boysdream#boyslife#boyscanrelate#relatable#relatablememes#reelsinstagram#reelfeelit#explore#exploremoretogether

Desi Memes Funny Jokes

@DESI_MEMES_Funny_Jokes · Post #5425 · 12.10.2024 г., 05:03

Earphone laga lena bhai 🎧 . #crusheverything#crush#crushlovers#sendthistoyourcrush#crushmemes#crushrejection#crush😍#crushquote#love#lovecrush#singlelifeproblems#singlefriends#singleme#singlelifebelike#singlemen#singleboy#single#boyswillbeboys#boystory#boysdream#boyslife#boyscanrelate#relatable#relatablememes#reelinstagram#reelfeelit#explore#exploremore