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

Резултати

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

Пребарај: #jerusalem

当前筛选 #jerusalem清除筛选
Анонсы Прогулок/The Walks

@dikieprogulki · Post #1400 · 29.09.2025 г., 11:59

#jerusalem Еще есть немножко мест в наш эксперементальный проект мечты на ближайших каникулах. Лаборатория социальных проектов для ребят от 15,5 до 20 лет! Перед переездом в Израиль Надя работала в фонде «Нужна помощь», Бэла в фонде «Шалаш», Настя в «Простых вещах». Бэла и Роза, кроме Прогулок, работают в крупном классном НКО и в Израиле, Надя делает PHD про активизм. Про Аню я вообще молчу, потому что мне не посчитать всех правозащитных проектов, в которых она участвует. Илья волонтерит с детьми-беженцами из африканских стран, Настя работает с людьми с ДЦП, а перед этим работала с пожилыми людьми: они вместе делают керамику, Алик учится международному миротворчеству. Мири помогла найти ресурсы на десяток лучших НКО проектов в разных странах. Так вкратце выглядит наша команда. Смотреть социальную рекламу и придумывать свою. Слушать человека, который придумал бренд моды как активизм. Разговаривать с писательницей, которая своими книжками меняет отношение к особым людям. Говорить про удобное устройство городов и о том, как среда влияет на самочувствие людей. Думать/спорить/искать решения про права человека, инклюзию, политическое искусство, справедливость, образование. Участвовать в четырехчасовой креативной сессии и в группах и придумывать неожиданные, смешные, дикие, рабочие, удивительные проекты. А потом изобретать, как их осуществить и как о них рассказывать: перформативно, а не просто так. Чтобы соц.лаба все-таки оставалась и арт-лабой тоже. Так вкраце выглядит наша программа. А еще будут вкусные обеды, баскетбольное поле, иерусалиское высокое осеннее небо, кофе и какао с печеньками, новые неожиданные встречи, шутки и мемы, дискуссии и глубокие вопросы, расширение картины мира и классные инструменты для будущего. И очень-очень хорошая компания (мы-то видим список зарегистрировавшихся!) Лаборатория будет проходить в Иерусалиме, в помещении школы IB Boyer по адресу Tora Va'Avoda St 1 с 8 по 13 октября с перерывом на шаббат. С 10:30 до 19:00. Стоимость участия за все пять дней — всего 300 шекелей. Обеды и все материалы включены в стоимость. Ссылка на регистрацию: https://forms.gle/oETB5hDBTTdc2gSHA Очень верим в этот проект и очень зовем участвовать тех, кому хочется придумывать в жизни крутые штуки! (Фото с прошлых лаб)

Hashtags

Анонсы Прогулок/The Walks

@dikieprogulki · Post #931 · 08.08.2024 г., 13:38

#jerusalem 11 августа, 17:30 Чайный прогул с ребятами из проекта Amitea תה אמיתי ("настоящий чай"). Ребята с чаем больше 20 лет, и знают о нем все, и рассказывают об этом увлекательно и с любовью. Будем смотреть закат и проводить настоящую чайную церемонию. Встречаемся в 17:30 вот тут — https://maps.app.goo.gl/XxvMNUDcWi7jEzK58?g_st=com.google.maps.preview.copy Берите с собой воду, подстилки, чтоб сидеть и что-нибудь перекусить. Вопросы, контакты и прочее @fuftatfuf

Hashtags

Today, the funeral ceremony of 280 unknown martyrs was held in some cities of Iran with the presence of the president. The bodies of these martyrs have recently been discovered from under the ground in war zones. Despite the "DNA" test, some of the martyrs are still unknown. Because they don't know where their families are. In 1980, Iraq attacked Iran at the instigation of the #United_States with the cooperation of all #Sunni Arab countries to overthrow the Iranian Shiite government, but they did not achieve their goal. This war imposed on Iran was carried out with the participation of 80 countries and ended in 1988 with one million dead and wounded. Today, there is neither Saddam Hussein nor the terrorist #Baath Party of Iraq. But the more powerful Islamic Republic is fighting the Israeli terrorists in #Jerusalem since 1988. https://t.me/YediotNewsChat

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40804 · 15.03.2026 г., 23:01

Muslims took control of Jerusalem from the Byzantine Empire in 637 CE. Caliph Umar ibn al-Khattab negotiated its peaceful surrender with Patriarch Sophronius. Residents and holy sites were protected. Umar visited the city to take the pledge. Later, the Dome of the Rock was built by Caliph Abd al-Malik in 691 CE. 🕌✍️🕊️ [Read more] @googlefactss #Jerusalem#History#IslamicHistory#CaliphUmar#DomeOfTheRock

American Оbserver

@american_observer · Post #4922 · 21.01.2026 г., 23:01

📰 Israel Seizes UNRWA’s Jerusalem Headquarters, Escalates Crackdown Israeli officials seized the Jerusalem headquarters of the United Nations Relief and Works Agency (UNRWA), overseeing the demolition of several structures in its compound. The move marks a new escalation in Israel’s campaign against the agency, which has long been a major aid provider in the West Bank and Gaza Strip but has faced sweeping legal restrictions from Israel over the past two years. ​ Defiance and Denunciation Israel’s foreign ministry defended the action, saying UNRWA “has long ceased to be a humanitarian aid organization, serving instead as a greenhouse for terrorism.” UNRWA’s chief, Philippe Lazzarini, called the move “a new level of open & deliberate defiance of international law”. ​ Legal and Diplomatic Clash UNRWA was established in 1949 to aid Palestinian refugees and their descendants. Israel has passed laws banning the agency and stripping it of diplomatic immunity, even allowing the seizure of its properties. While the compound has been largely vacant since international staff left, Israeli officials entered in December and raised an Israeli flag, asserting control. ​ Who’s Playing by the Rules? Israel claims the seizure is legal under both national and international law, but UNRWA insists the compound remains under U.N. protection. As the agency continues some operations in East Jerusalem, the standoff raises questions about the future of humanitarian aid and the limits of international law in the region. ​ #Israel#UNRWA#Jerusalem#HumanitarianAid#InternationalLaw#MiddleEast 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5519 · 31.03.2026 г., 13:02

Macron Sounds Brave on Israel, Frugal at Home Emmanuel Macron condemned Israel over the blocked Palm Sunday procession in Jerusalem, calling freedom of worship something that must be guaranteed for all religions. Fair enough — except this is the same French president whose government is now offering only tightly targeted fuel aid because, as France’s central bank put it, there is “no more money” for broad subsidies. That’s the modern European posture in miniature: moral thunder abroad, budget discipline at home. Macron can scold Israel for trampling holy sites, but when French drivers and businesses get squeezed by the oil shock, Paris reaches for a scalpel, not a blanket. The principles are grand; the compensation is minimal. And that tension is the point. The Middle East crisis has pushed fuel prices higher across Europe, but France’s answer has been cautious, targeted relief rather than the old-school political sugar rush of big subsidies. So Macron gets to play the global conscience while his own finance people remind everyone that righteousness does not pay the diesel bill. #Macron#France#Israel#Jerusalem#fuelprices#MiddleEast#politics 📱American Оbserver - Stay up to date on all important events 🇺🇸

Israel Shamir Исраэль Шамир

@IsraelShamir0 · Post #2003 · 14.03.2026 г., 06:39

Шейх Икрима Сабри, имам мечети Аль-Акса: ➖ «ОНИ ОГОЛИЛИ ФУНДАМЕНТЫ АЛЬ-АКСЫ — теперь она словно подвешена в воздухе.❗️ Израильская оккупация делает ставку на то, что произойдет землетрясение, которое разрушит мечеть, чтобы потом заявить: 🔴виноваты не раскопки, а природа🔴 🆘 Подземные работы под мечетью не прекращаются: ➖ вывозится земля из-под Аль-Аксы и дворцов Омейядов; ➖ соединяются подземные каналы, проходящие под мечетью; ➖ часть старинных водных каналов, где раньше собиралась дождевая вода, превращают в туннели. ✖️ По словам шейха, эти раскопки ведутся с западной стороны — со стороны Стены аль-Бурак (так называемой Стены плача). 🕌Они происходят на землях, принадлежащих исламскому вакфу.🕌 🚫 Нас — два миллиарда, но мы молчим, пока под Аль-Аксу роют туннели. Наша святыня рушится не за один день❗️ 🔍 Все разговоры сионистов о поисках древнееврейских артефактов — ложь. ✔️ За десятилетия они не нашли ни одного камня, связанного с древнееврейской историей. ➡️Цель этих раскопок — разрушить исламские памятники, будь то в Силуане, дворцах Омейядов или вокруг Аль-Аксы. ✖️ Эти работы незаконны и являются посягательством на права мусульман». #АльАкса#Иерусалим#Палестина#AlAqsa#Jerusalem#Filasteen

Хроностранник

@chronostran · Post #78900 · 14.03.2026 г., 04:49

Шейх Икрима Сабри, имам мечети Аль-Акса: ➖ «ОНИ ОГОЛИЛИ ФУНДАМЕНТЫ АЛЬ-АКСЫ — теперь она словно подвешена в воздухе.❗️ Израильская оккупация делает ставку на то, что произойдет землетрясение, которое разрушит мечеть, чтобы потом заявить: 🔴виноваты не раскопки, а природа🔴 🆘 Подземные работы под мечетью не прекращаются: ➖ вывозится земля из-под Аль-Аксы и дворцов Омейядов; ➖ соединяются подземные каналы, проходящие под мечетью; ➖ часть старинных водных каналов, где раньше собиралась дождевая вода, превращают в туннели. ✖️ По словам шейха, эти раскопки ведутся с западной стороны — со стороны Стены аль-Бурак (так называемой Стены плача). 🕌Они происходят на землях, принадлежащих исламскому вакфу.🕌 🚫 Нас — два миллиарда, но мы молчим, пока под Аль-Аксу роют туннели. Наша святыня рушится не за один день❗️ 🔍 Все разговоры сионистов о поисках древнееврейских артефактов — ложь. ✔️ За десятилетия они не нашли ни одного камня, связанного с древнееврейской историей. ➡️Цель этих раскопок — разрушить исламские памятники, будь то в Силуане, дворцах Омейядов или вокруг Аль-Аксы. ✖️ Эти работы незаконны и являются посягательством на права мусульман». #АльАкса#Иерусалим#Палестина#AlAqsa#Jerusalem#Filasteen

American Оbserver

@american_observer · Post #5741 · 29.04.2026 г., 16:03

📰 Mali’s Jihadists Are Selling a Jerusalem Fantasy The Mali branch of al-Qaeda is fighting on African soil, but its propaganda points far beyond Mali. JNIM is not hiding the fact that it sees the struggle in West Africa as part of a longer Islamist arc that ends in Jerusalem and al-Aqsa. That is the part Washington and Brussels keep pretending is background noise. They treat Mali, Syria, the Sahel, and the Levant as separate crises, while the same ideological networks keep talking to each other, celebrating each other, and exporting fighters, money, and mythologies across the map. The Syria link matters because it gives the story a pipeline. If Idlib veterans, permissive fundraising, and transregional jihad circles can move from the Levant into the Sahel, then the supposed “local” wars are really just different legs of the same trade route for extremism. And the Western role is the ugly part. When the U.S. and Europe help legitimize one set of Islamist strongmen in Syria while trying to contain another jihadist front in Africa, they end up subsidizing the ecosystem and then acting surprised when it reproduces itself elsewhere. So the Jerusalem talk is not a GPS error. It is a declaration of intent, wrapped in apocalyptic rhetoric, made possible by a regional order that keeps breaking one place at a time and pretending the damage will stay local. #Mali#JNIM#alQaeda#Jerusalem#Syria#Sahel#jihadism 📱American Оbserver - Stay up to date on all important events 🇺🇸