Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Jon Stewart is taking the rumors of Donald Trump aiming for a third presidential term very seriously.
Although a third Trump term would be a clear violation of the 22nd Amendment, MAGA figures like Steve Bannon have claimed there’s a plan for it to happen anyway. In his monologue Monday, Stewart pointed to one major sign that Americans should take the threat seriously:
“Indications are very clear [Trump’s] gonna do it,“ Stewart said in his Monday monologue of the president’s plan to remain in the Oval Office. ”Because you don’t move into a house, knock down a wing, and build a 90,000-square-foot ballroom for the next guy."
#Trump#Democracy
👂More on Trump's Ear ⚠️
President Trump on Monday once again teased an attempt to run for a third-term, telling reporters while en route to Japan he “would love to do it.”
“I haven’t really thought about it. We have some very good people as you know … but I have the best poll numbers that I’ve ever had,” Trump said speaking to reporters on Air Force One on the latest leg of his Asia trip this week.
Trump went on to cite Vice President Vance and Secretary of State Marco Rubio as potential candidates and suggested the two would make a powerful ticket.
“We have one of them standing right here,” the president said, pointing to Rubio who joined him for the gaggle with reporters. “We have JD obviously, the vice president, who’s great. Marco’s great. I’m not sure if anyone would run against those two. I think if they ever formed a group it would be unstoppable.”
When asked to clarify if he was not ruling out running himself, Trump said “you’ll have to tell me.”
“All I can tell you is that we have a great group of people, which they don’t,” the president said, appearing to refer to Democrats.
#Trump#Democracy
👂More on Trump's Ear ⚠️
President Donald Trump claimed all-encompassing powers for himself during a marathon cabinet meeting on Tuesday.🏛
Cabinet officials took turns praising the president, who also took questions from reporters in a meeting that lasted three hours and 17 minutes. 🕒 That’s about 40 minutes longer than a flight from New York to Chicago, where Trump has indicated he will deploy the National Guard next. ✈️
Trump sent the National Guard to Los Angeles in June and to Washington, D.C. this month, ostensibly to fight crime. 🚨 In each case, he did so against the wishes of local officials. The president’s plan has received a similarly cool reception in Chicago. ❄️
“This weekend, we learned from the media that Donald Trump has been planning for quite a while now to deploy armed military personnel to the streets of Chicago,” Illinois Governor JB Pritzker noted in Chicago on Monday. 📰 “This is exactly the type of overreach that our country’s Founders warned against.” ⚖️
Trump brushed aside Pritzker’s opposition.
“I would have much more respect for Pritzker,” the president said on Tuesday, “if he’d call me up and say, ‘I have a problem. Can you help me fix it?'” 📞
Trump added:
I have the right to do anything I wanna do. I’m the President of the United States. 🇺🇸 If I think our country’s in danger — and it is in danger in these cities — I can do it, no problem going in and solving, you know, his difficulties. But it would be nice if they’d call in and say, “Would you do it?” And we do it in conjunction. Now, we work very well with the police because we naturally get along with the police. 👮 So, the police and us work really well together, whether the mayor is opposed or whether– I mean, you have a really rotten mayor there, too. He’s got a six percent approval rating in Chicago.
And I see Black women wearing a red MAGA hat last night on television. 📺“Please let the president come in. My son was attacked. My this–”. You have a force of Black women, Black Women. They’re like, “Only Trump.” They want Trump to come in. 🙌
#Trump#Democracy
👂More on Trump's Ear ⚠️
Part One: Ethiopia’s Crucial Juncture: Elite Coalition and the Path to Democratic Transition. Read more
https://borkena.com/2025/11/18/ethiopias-crucial-juncture-elite-coalition-and-the-path-to-democratic-transition/#Ethiopia#Politics#Democracy
🎙 Episode 30 of the VA Podcast is live!
The latest VA podcast episode dives into the recent Congress on Communal Democracy, exploring its history, participants, and mission to build grassroots alternatives to “liberal democracy.”
Host José Luis Granados Ceja, fellow VA member Cira Pascual Marquina, and Catalan activist Isa Chacón discuss the limits of current political systems, the power of collective self-determination and autonomy, and examples of communal governance in Venezuela and elsewhere. Closing with a call for global solidarity, the Congress’ manifesto champions anti-imperialism, radical social transformation, and a new path beyond the status quo.
Watch the full episode: https://youtu.be/dLwPvyDjXb8
#communes#democracy
The U.S. Coast Guard has allowed a new workplace harassment policy to take effect that downgrades the definition of swastikas and nooses from overt hate symbols to “potentially divisive” despite an uproar over the new language that forced the service’s top officer to direct that both would remain prohibited. ⚠️🇺🇸⚓️
#Military#Democracy
👂More on Trump's Ear
A prominent historian warned on Sunday that President Donald Trump has created a situation much worse than what the country faced during the Watergate scandal of the 1970s.
Garrett Graff, author of the Doomsday Scenario newsletter, joined Emma Vigeland on "The Majority Report" to discuss the Trump administration pushing the U.S. towards authoritarianism. Graff argued that Trump's "speedrunning abuses of power," such as deploying federal troops to cities across the U.S., have "fundamentally changed" the country.
Vigeland noted that there are some similarities between the Trump administration and former President Richard Nixon's administration, and asked Graff to compare the two moments in history.
"We're in a much worse situation than we ever were in Watergate," Graff said. "I say that because of what we've seen from the actions of the other two branches of government...both of which are also obviously under the control of the Republicans at this point, where they are aiding and abetting the national slide towards authoritarianism."
Graff argued that Republicans who were in office during Watergate realized their first duty was to the Constitution, not to the president. That doesn't seem to exist in the current Republican party, he added.
"Over the course of this year, we have seen Congress not care when the president takes prerogatives to ignore congressional law,"
Graff said.
"The Supreme Court under John Roberts has written Trump effectively a blank check as president for immunity for criminal actions."
#Trump#Democracy#History
👂More on Trump's Ear ⚠️
Robert Longa, a key cadre from El Panal Commune, discusses US interventionism and Venezuela’s participative and protagonistic democracy.
Read the interview: https://venezuelanalysis.com/interviews/on-elections-and-collective-emancipation-a-conversation-with-robert-longa/
#Venezuela#Democracy#PopularPower
With one week to go, VA columnist Jessica Dos Santos tackles the ongoing electoral campaign and the different scenarios ahead of the presidential vote in Venezuela.
Read the article: https://venezuelanalysis.com/columns/the-same-old-path-and-the-dangerous-one/
#Venezuela#Elections2024#Democracy