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

Резултати

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

Пребарај: #babur

当前筛选 #babur清除筛选

👳‍♀14-fevral – Zahiriddin Muhammad Bobur tavallud topgan kun Bobur (1483–1530) – buyuk o‘zbek shoiri, mutafakkir, tarixshunos va davlat arbobi, Boburiylar sulolasi asoschisi. “Boburnoma” va g‘azallari orqali u sevgi, vatan, inson qadri va adolat g‘oyalarini tarannum etdi. Bobur merosi millatimiz iftixori __________ 👳‍♀14 февраля - день рождения Захириддина Мухаммада Бабура Бабур (1483-1530) - великий узбекский поэт, мыслитель, историк и государственный деятель, основатель династии Бабуридов. Через "Бабур-наме" и газели он воспевал идеи любви, родины, человеческого достоинства и справедливости. Наследие Бабура - гордость нашего народа __________ 👳‍♀February 14 - Zahiriddin Muhammad Babur's birthday Babur (1483-1530) - a great Uzbek poet, thinker, historian and statesman, founder of the Baburid dynasty. Through his "Baburnama" and ghazals, he celebrated the ideas of love, homeland, human dignity and justice. Babur's legacy is the pride of our nation #GSBE#GraduateSchool#Babur#King#Poet 🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40836 · 20.03.2026 г., 23:10

Part 2: Babur, at age 13, wrote in the Baburnama about his feelings for a boy named Baburi: > “In those leisurely days, I discovered in myself a strange inclination — nay! as the verse says, ‘I maddened and afflicted myself’ — for a boy in the camp‑bazar, his very name, Bāburī, fitting in. Up till then I had had no inclination for anyone… From time to time Bāburi came to my presence but out of modesty I could never look straight at him… I got so confused that I almost went right off.” 💌📖👑 Note: this does not mean he was homosexual. Such feelings can be a normal part of teenage self-discovery. @googlefactss #Baburnama#Babur#MughalHistory#HistoricalFacts#LoveInHistory#Memoir#HonestWriting

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40835 · 20.03.2026 г., 23:01

Part 1: Babur, the Mughal emperor and a Muslim, wrote the Baburnama, a detailed personal memoir. In it, he shared his feelings openly. He wrote about his love and admiration for women. He also felt strong affection and admiration for a boy named Baburi. He described these emotions with honesty and detail. He sometimes wrote poems about his feelings. His writing shows both his emotional sensitivity and his poetic talent. He mixed personal experiences, romantic feelings, and reflections on life. Babur’s memoir is considered important for both history and literature. It gives a rare glimpse into his private thoughts, he was not afraid to show his personal desires and emotions. Both his relationships with women and his emotional attachment to Baburi are part of the memoir. His writing style is clear, candid, and expressive. The writings are valued for its literary quality and honesty. 💌📖👑🕌 [Read more1] [Read more2] @googlefactss #Baburnama#Babur#MughalHistory#HistoricalFacts#LoveInHistory#Memoir#Islam