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

Пребарај: #jigjiga

当前筛选 #jigjiga清除筛选
Addis Standard

@addisstandardeng · Post #21596 · 03.03.2026 г., 15:51

Memorial park honoring prominent #Somali anti-colonial leader Sayyid Mohammed Abdullah Hassan inaugurated in #Jigjiga A new memorial park honoring Sayyid Mohammed Abdullah Hassan, the early 20th century Somali scholar, poet and anti-colonial military leader, has been officially inaugurated in Jigjiga, capital of #Ethiopia’s Somali Regional State. Known in Somali as Maxamed Cabdulle Xasan, Sayyid Mohammed Abdullah Hassan is know to have founded and led the Dervish movement, which waged armed resistance against #British, #Italian and Ethiopian colonial expansion in the Somali Peninsula. While widely revered by many Somalis as a symbol of anti-colonial struggle, he was pejoratively labeled the “Mad Mullah” by the British Empire. In 1917, the Ottoman Empire recognized him as the “Emir of the Somali People.” Regional President Mustafa Muhummed presided over the ribbon-..... https://web.facebook.com/AddisstandardEng/posts/pfbid035zhG5D71mJR7UdFHybuQqaDPAcU8msaQNqQShDRQ5NYGVkbYXYFHbQGW62n97vmrl

Addis Standard

@addisstandardeng · Post #21260 · 31.01.2026 г., 08:11

News: PM Abiy receives #Djibouti and #Somalia presidents amid shifting regional security alignments Prime Minister #Abiy_Ahmed on Saturday received President of Djibouti Ismail Omar Guelleh and President of Somalia Hassan Sheikh Mohamud at #Jigjiga Airport, the Ministry of Foreign Affairs said, against the backdrop of intensifying diplomatic and security realignments in the Horn of Africa and the #Red_Sea region. The brief statement by the Ministry, issued on 31 January, did not provide details on the purpose or agenda of the leaders’ arrival in Jigjiga. The visit comes three weeks after Abiy traveled to Djibouti on 11 January for talks with President Guelleh and a tour of the Port of #Doraleh, following #Egypt’s signing of cooperation agreements with Djibouti on port development, logistics, and renewable energy. At the time, Abiy said discussions focused on ... https://www.facebook.com/AddisstandardEng/posts/pfbid02btcBVYhoVm2sSaWhGDni6vmXgSSePTnv598gAea8DcrwpE4QBC7vA24HoQQh8kYKl