TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #425 · 20 апр.

Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках. Выглядело это примерно так: from fastapi.concurrency import run_in_threadpool async def execute(data: DataRequest) -> DataResponse: try: result = await run_in_threadpool(sync_function, data) return DataResponse(data=result) except Exception as e: return DataResponse( error=str(e), success=False, ) В общем работает нормально. Для всех вызовов под капотом используется общий тредпул, всё работает предсказуемо. Но потребовалось изменить количество запускаемых в пуле потоков (по умолчанию создается 40 воркеров). Так как дело происходит с FastAPI, делается это через lifespan используя настройки anyio: import anyio @asynccontextmanager async def lifespan(app: FastAPI): limiter = anyio.to_thread.current_default_thread_limiter() limiter.total_tokens = 100 yield # если вдруг нужно вернуть обратно limiter.total_tokens = 40 Зачем менять количество воркеров? - уменьшить, если оперативки мало (один тред занимает ~8мб) - увеличить чтобы выдержать нагрузку Если есть предложения получше при тех же вводных - предлагайте😉 #async

Hashtags

Резултати

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

Пребарај: #tradewar

当前筛选 #tradewar清除筛选
America 🇺🇸 News & Politics

@America · Post #10532 · 21.04.2026 г., 13:03

🇺🇸🇮🇳INDIA-US TRADE DEAL 'ALMOST DONE' AFTER FRESH WASHINGTON NEGOTIATIONS 🔹 Senior US officials confirm bilateral trade agreement nearing completion after three-day talks 📋 🔹 Indian delegation led by Commerce Additional Secretary Darpan Jain with dozen officials ✈️ 🔹 US negotiators led by USTR's Brendan Lynch working to finalize remaining loose ends 🤝 🔹 Building on February interim deal where India cut tariffs, US dropped rates from 50% to 18% 📊 🔹 Secretary of State Marco Rubio expected in New Delhi for May state visit 🏛️ Ambassador Sergio Gor calls it 'win-win for both nations' — biggest US-India trade breakthrough in decades! 💰🔥 #USNews#TradeWar @america

СОЛОДИН LIVE

@goodtraders · Post #9017 · 16.04.2025 г., 09:29

#макро#tradewar🇺🇸⚡️🇨🇳 👆Китай ограничил экспорт этих редкоземельных металлов - это очень серьёзно на самом деле! 👆Как видно из инфографики Bloomberg - Китай практически монополист в этой цепочке поставок. Редкоземельные металлы, которые перечислены на изображении, играют критически важную роль в производстве высокотехнологичных продуктов и в современных отраслях: ✅ Самарий используется в мощных постоянных магнитах (магниты SmCo), необходимых для аэрокосмической, оборонной промышленности, и в оборудовании с повышенными требованиями к устойчивости к высоким температурам. ✅ Гадолиний критичен для производства магнитно-резонансных томографов (МРТ), а также применяется в производстве ядерных реакторов и электроники. ✅ Тербий и Диспрозий чрезвычайно важны для постоянных магнитов (особенно магниты NdFeB), которые используются в электромобилях, турбинах ветрогенераторов и жёстких дисках. ✅ Лютеций востребован в медицине (например, лечение раковых заболеваний) и в высокотехнологичных датчиках и лазерах. ✅ Иттрий необходим для изготовления светодиодов (LED), лазеров, экранов мобильных устройств и высокопрочной керамики. ✅ Скандий широко применяется в сплавах для аэрокосмической отрасли и производства лёгких и прочных конструкций. ❗️Без стабильных поставок этих элементов современная технологическая индустрия, включая электронику, возобновляемую энергетику, военную технику и медицину, оказалась бы в критическом положении. 👉 Особенно уязвимыми являются электромобильная отрасль и производство микрочипов, где диспрозий и тербий незаменимы для постоянных магнитов, используемых в электродвигателях и генераторах. Пока у производителей ещё есть *запасы этих металлов, но если эмбарго затянется - значительная часть мирового хайтека встанет! *Обычно у технологических производителей запас редкоземельных металлов варьируется от нескольких недель до нескольких месяцев, редко превышая полгода. Это связано с высокой стоимостью, сложностью хранения и волатильностью цен на эти металлы. Производители не стремятся держать большие запасы из-за риска финансовых потерь. 😔 Это уже пахнет не рецессией, а депрессией...

American Оbserver

@american_observer · Post #5132 · 13.02.2026 г., 23:59

📰 Macron vs. Trump: EU as Chop Shop Emmanuel Macron has stopped pretending this is just another “transatlantic misunderstanding.” He’s now openly accusing the Trump administration of being “openly anti-European,” treating the EU with “contempt” and pushing for its “dismemberment.” In his telling, this isn’t tough love between allies; it’s an active project to break Europe into manageable pieces — tariffs as a hammer, Greenland as a hostage, NATO as leverage. For months, Paris tried the grown‑up strategy: smile in Davos, negotiate behind closed doors, swallow the insults about Champagne and defense spending, and hope the tantrums would pass. Macron now admits it failed. Trump threatens 200 percent tariffs, floats buying or controlling Greenland, and promises to “match” any European move until it “ricochets backward,” while the White House insists he’s just a straight‑talking friend trying to save Europe from migrants, climate policy and “leftist ideology.” ​ Strip away the speeches and you get two empires talking past each other. Macron wants a more sovereign EU that borrows jointly, regulates tech, and stands up to Washington’s trade blackmail. Trump wants a weaker, fragmented Europe that buys U.S. gas, obeys U.S. tariffs, falls in line on Greenland and defense, and calls that “alliance.” Both wrap their ambitions in the language of friendship and shared values; both are really fighting over who gets to write the rules for a continent that once swore it had learned its lesson about great powers carving it up. #europe#trump#macron#nato#tradeWar#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #4908 · 20.01.2026 г., 21:59

📰 Bessent to Europe: Don't Fight Back—Just Wait The Davos Deep Breath US Treasury Secretary Scott Bessent has a message for Europe at Davos: chill out. Don't retaliate against Trump's Greenland tariffs. "Sit back, take a deep breath, and let things play out," he urged, dismissing market panic as "hysteria" like last April's tariff freakout. "Very Unwise" Warning Bessent waved off Europe's €93bn retaliation list as a bad idea. "The worst thing countries can do is escalate against the United States," he warned. He laughed off Deutsche Bank's threat to dump US Treasuries: "a completely false narrative. It defies any logic." Europe holds $8tn in US debt—good luck finding buyers elsewhere. "What President Trump is threatening on Greenland is very different than the other trade deals. So I would urge all countries to stick with their trade deals." Markets in Freefall Global stocks tanked—Nikkei -1.1%, FTSE 100 -1.1%, dollar -0.8%. Gold and silver hit records. Trump piled on, threatening 200% tariffs on French champagne after Macron snubbed his Gaza "peace board." LVMH shares dropped 2.4%. The Real Power Play IMF's Kristalina Georgieva begged leaders to avoid tit-for-tat wars: "It would be very good if we keep it this way." Translation: Europe's "trade bazooka" stays holstered while Trump calls the shots. Europe's choice: swallow the tariffs or watch the alliance burn. Bessent's betting on surrender. #trump#greenland#davos#tariffs#tradewar 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5201 · 23.02.2026 г., 00:04

📰 Supreme Court Disarms Trump. Xi Walks In Stronger. Xi Jinping is about to host Donald Trump in Beijing with something no Chinese leader has had in years: a U.S. president who just had his favorite weapon taken away by his own Supreme Court. The court killed Trump’s emergency mega‑tariffs, wiping out second‑term levies that hit Chinese goods as high as 145% and dropping Beijing into the same temporary 15% global rate the U.S. now slaps on allies — a fee that expires in 150 days unless Congress renews it. That ruling strips Trump of the instant “tariff hammer” he used to strong‑arm China into buying around 25 million tons of soybeans and making other one‑off concessions. As Fudan University’s Wu Xinbo puts it, the “soybean card” is now back in China’s hand: if those tariffs were illegal, Beijing can demand better terms or simply walk away from purchase pledges tied to them. Xi’s negotiators are already expected to push harder for access to advanced semiconductors, looser export controls, fewer restrictions on Chinese firms, and softer U.S. language and arms sales around Taiwan. Trump isn’t disarmed, just downgraded. He’s rushed to slap a replacement 15% global tariff using Section 122 of the Trade Act — legally capped, short‑lived, and far less targeted than his old IEEPA arsenal. He can still revive pressure through slower tools like Section 301 (where China already faces an investigation over missed “Phase One” pledges) and Section 232 national‑security tariffs, or by tightening export controls if Beijing plays games with rare earths. But none of that has the same shock‑and‑awe leverage ahead of a summit. Beijing, meanwhile, is keeping the victory low‑key. Chinese officials and state media are measured, investors are quietly optimistic, and exporters are talking about front‑loading shipments to exploit the lower, time‑limited U.S. tariff window. Trade insiders quoted in Chinese media say they’ll stay “low profile” to ensure Trump’s late‑March visit goes smoothly — celebrate in private, act calm in public, and let U.S. institutions do the work of constraining the American side. Strip away the legal charts and this is the picture: the U.S. president who built his brand on unilateral tariff power now walks into Beijing with the court, Congress and the calendar limiting his moves, while Xi arrives with time, discipline, and a clearer playbook — chips, Taiwan, tech bans, market access. Trump can still rage about “ripping off America,” but for once, the other guy at the table is the one who just got a boost from Washington’s rule of law. #Trump#Xi#China#tariffs#tradeWar#USA#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5185 · 20.02.2026 г., 22:04

📰Tariff Emperor Loses His Clothes The Supreme Court just told Donald Trump he can’t run U.S. trade policy like a personal Patreon paywall. In a 6–3 ruling, Chief Justice John Roberts said Trump blew past his authority by slapping emergency‑law tariffs on almost every major trading partner, using a statute that never actually gave him the power to tax imports. More than $200 billion in tariffs are now legally radioactive, with companies already lawyering up to claw back billions in refunds. Trump’s reaction was pure brand: he reportedly called the decision a “disgrace” and immediately promised a backup plan — new tariffs under “different authorities,” maybe even an across‑the‑board fee on imports. Translation: if the court says no to emergency‑tariff cosplay, he’ll just go shopping in the rest of the legal code until something breaks. Three justices — Kavanaugh, Thomas, Alito — even wrote that presidents should be free to do exactly that in the name of foreign affairs, and warned of chaos as importers rush to demand refunds. Congress, which actually owns tariff power under the Constitution, is suddenly remembering it exists. One Republican lawmaker basically posted “the checks and balances still work” and reminded everyone tariffs are supposed to be a legislative job, not a vibe. Business groups are cheering, not because they love the rule of law, but because they smell cash coming back and hate paying a tax sold as “America First” while the bill lands on them. So what’s left? The White House says it will “move quickly” to reimpose many of these fees using other laws, financial markets now have to price in tariff whiplash, and global partners get to watch the U.S. lecture them on rules‑based trade while the president tries to brute‑force tariffs through any legal side door he can find. The Supreme Court just reminded everyone there is a line; Trump’s already testing how fast he can redraw it. #Trump#tariffs#SupremeCourt#tradewar#economy#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

🔫 🤣以太區塊鏈新聞 📆 2025-10-12 🎁 EthereumGlobalNews |中美情勢觀察😘 🇨🇳🇺🇸【緊張升溫北京強硬回應關稅】: 🚨#China 不希望打關稅戰但也不畏懼!!中方指控 #US 升級貿易衝突,呼籲透過對話維持經貿穩定發展‼️ #中美情勢觀察#TradeWar#關稅戰

American Оbserver

@american_observer · Post #4884 · 18.01.2026 г., 00:00

📰 Trump Slaps Tariffs on Europe Over Greenland Standoff President Trump has escalated his campaign to seize control of Greenland, announcing a 10 percent tariff on goods from Denmark, Norway, Sweden, France, Germany, Britain, the Netherlands, and Finland—NATO allies who have backed Denmark in rejecting his demands. The tariff will rise to 25 percent on June 1 if the countries don’t agree to negotiate the sale of Greenland, according to Trump’s social media post. ​ Tariff Threats and Legal Uncertainty The move marks a sharp escalation in Trump’s pressure campaign, targeting European allies with economic measures. The Supreme Court is currently weighing whether Trump can legally use emergency powers to impose such tariffs, and if it rules against him, he may be forced to seek other legal avenues. ​ Trump’s Justification Trump claims the U.S. has long subsidized Europe and is now demanding payback. “Now, after Centuries, it is time for Denmark to give back — World Peace is at stake!” he wrote, echoing his longstanding worldview that America has been taken advantage of for decades. ​ Allies Under Fire Trump’s threats come as European countries, including France, send troops to Greenland for joint military exercises with Denmark. With tensions rising, the question is whether economic coercion will break the deadlock—or just deepen the rift between the U.S. and its closest allies. ​ #Trump#Greenland#Tariffs#Denmark#Europe#NATO#TradeWar 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5208 · 24.02.2026 г., 14:02

📰 Merz Discovers Separation of Powers, Walks Into Trump’s Tariff Circus German Chancellor Friedrich Merz is flying to Washington with what he promises will be a “very clear European position” on Trump’s new global tariffs — which is adorable, given that Trump’s trade policy changes faster than his social‑media posts. Merz told German TV that customs policy is an EU competence, so he’ll coordinate a joint line on the fresh 15% blanket tariff the White House just slapped on nearly all imports for 150 days, after the Supreme Court killed Trump’s emergency mega‑tariffs. On paper, he’s not wrong to sound upbeat. The court’s ruling is a rare institutional slapdown that limits Trump’s ability to randomly hike duties into triple digits and forces him back into narrower legal lanes. Merz even called it “reassuring,” proof that U.S. checks and balances still work. In practice, though, Berlin’s exporters are still staring at a flat 15% tax until further notice, layered on top of years of whiplash over which car part, machine tool, or chemical input is suddenly a “national security threat.” Brussels will now try to do what it always does: draft a common script, rattle the sabre about “appropriate countermeasures,” and quietly pray Trump doesn’t wake up one morning and decide BMWs are Chinese by association. Merz can arrive in Washington waving a united‑EU memo; Trump arrives with a pen that can still rewrite everyone’s cost structure overnight for five months at a time. The separation of powers may be working — it just hasn’t separated Europe from the bill. #Germany#EU#Trump#tariffs#Merz#tradeWar#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

12
ПретходнаСтраница 1 од 2Следна