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

Резултати

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

Пребарај: #nietzsche

当前筛选 #nietzsche清除筛选
Aesthetica

@Aetatesolis · Post #4360 · 19.04.2025 г., 17:21

"He who can not obey himself will be commanded." -Nietzsche The line cuts deep because it's true. We've all felt it. The moment we betray what we know we should do. The quiet voice we ignore until someone louder takes control. Do shout to yourself. #discipline #nietzsche AETATESOLIS

Aesthetica

@Aetatesolis · Post #3962 · 28.02.2025 г., 22:15

🏛Nietzsche's The Last Man "The earth hath then become small, and on it there hoppeth the last man who maketh everything small. His species is ineradicable like that of the ground-flea; the last man liveth longest." - Nietzsche Nietzsche wrote about what he called "The Last Man". The Last Man wants everyone to be the same, to have the same, and to say the same thing. The Last Man wants to feel confident that everything is known and understood and is being handled correctly. The Last Man finds reassurance in collective consensus, which he values more highly than truth or excellence. The Last Man is a flat line - incapable of awe or passion or the creation of values. #nietzsche #zarathustra *Picture: Starttheworld AETATESOLIS

Rick DuFer & Daily Cogito Channel

@filosofarsogood · Post #12497 · 26.04.2025 г., 10:58

Se il 29 aprile "Dio era morto", a fine maggio sarà sicuramente "Rick DuFer è morto" 😂 Con l'uscita del nuovo libro per Feltrinelli abbiamo un po' esagerato con l'organizzazione delle presentazioni, ma ho così tante cose da raccontarvi che non ho potuto resistere. Ci vediamo un po' dappertutto, presto arriveranno date anche al sud, ma nel frattempo Roma, Torino, Milano, Cesena e tante altre città saranno raggiunte! Spero di vedervi numerosi, questo libro non vi lascerà indifferenti. Tutte le info qui: https://www.dailycogito.com/eventi #rickdufer#dioeramorto#filosofia#feltrinelli#instabook#eventi#dalvivo#dailycogito#renatominutolo#nietzsche