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

Резултати

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

Пребарај: #sanders

当前筛选 #sanders清除筛选
Trump's Ear

@trumpsear_tg · Post #1595 · 02.10.2025 г., 20:01

Sen. Bernie Sanders (D-VT) got animated during an interview with CNN's Kaitlan Collins on Tuesday night over President Donald Trump's latest threat to withhold federal funding from New York City. Sanders joined Collins to discuss the looming government shutdown. He expressed concern that the Trump administration could use the shutdown to continue advancing its authoritarian agenda, citing previous examples like firing workers that "they don't like" from the Veterans Administration and making significant cuts to Medicaid. "I'll give you another example, as I'm sure you've heard of it," Sanders told Collins. "I think it was yesterday. Trump says, 'Well, if Mr. [Zohran] Mamdani becomes the mayor of New York City, then I'm going to cut funding from New York City.'" #Trump#Sanders 👂More on Trump's Ear ⚠️

Trump's Ear

@trumpsear_tg · Post #1727 · 03.11.2025 г., 17:59

✊ As Senator Bernie Sanders and Representative Alexandria Ocasio-Cortez joined Zohran Mamdani on Sunday at Forest Hills Stadium, a bigger test for the left may still lie ahead. 🌆📣 #NY#Mamdani#Sanders 👂More on Trump's Ear ⚠️

Libertà è ragione

@libertaeragione · Post #4118 · 12.02.2024 г., 08:37

#USA#Ucraina#Israele#Taiwan Il #Senate ha approvato, con 67 voti favorevoli e 27 contrari, la chiusura dell’accordo per la fornitura di aiuti per un ammontare pari a 95 miliardi di dollari a Ucraina, Israele e Taiwan. Anche 18 senatori repubblicani hanno votato a favore dell’accordo, mentre Bernie #Sanders (#D|Centro-sinistra) è stato l’unico dem ad opporsi alla fornitura di aiuti a tali nazioni. @OsservatorioEsteri