Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🇫🇷The presence of 4 thousand French soldiers in the Gaza war
Thomas Bourtes, a member of the #French parliament, announced that more than 4,000 French citizens are participating in the Israeli army in the war against Gaza.
La présence de 4 mille soldats français dans la guerre à Gaza
Thomas Bourtes, député français, a annoncé que plus de 4 000 citoyens français participent à l'armée israélienne dans la guerre contre Gaza.
https://t.me/YediotNewsChat
Еще одна полезная рекомендация для french learners:
https://youtube.com/playlist?list=PLycTNLUo2y2EAKEhVfxB9gYo6r0OTMgM0&si=SBoZIA4aZQhFpzMl
Очень классный подкаст, легко понять и даже есть транскрипт, если слушать на сайте
#french
Я довольно неплохо понимаю текста, которые читаю на французском и после этого фото поняла почему😆
Но я понимаю, что словарный запас надо расширять, поэтому решила, что буду больше читать. С английским было так же, больше всего слов я выучила после фокуса на чтение
#french
#Rap#French
Manau le curé et les Loups
It speaks of a priest guarding a village against a wolf pack, the priest speaks of his regrets and the things he would have liked to do in his life.
In the end, as the sun clears the night, the villagers find the priest dead, killed by the wolves as he was protecting the village.
https://youtu.be/UEpzez_H2CI
After calling the #Hijab “a symbol of women’s submission to men”, #French Interior Minister continues his #Islamophobic comments, calling the Hijab “a sign of inferiority.”
#Op_ed: #Djibouti: Pillar of stability, not a "rentier fortress" in decline
In a rebuttal to an op-ed titled "Crumbling of Rentier Fortress: Ethiopia’s Maritime Pivot, Decline of Djibouti’s Monopoly," Naguib Ali Taher, Communications Officer for the Republic of Djibouti, firmly rejects the characterization of his nation as a “crumbling rentier fortress.” He dismisses the portrayal as both “inaccurate and dismissive,” arguing that it misrepresents the geopolitical reality of the Horn of Africa.
Taher contends that Djibouti remains “an undeniable bedrock of stability” within a volatile region—a status validated by the presence of major #American, #French, #Chinese, and #Japanese military installations.
The author further brushes aside accusations of authoritarianism and regional meddling, labeling them "tabloid-style slander."
https://addisstandard.com/?p=55291
#Vocabee#Snap#amp#Learn#French
Join the Vocabee: Snap & Learn French beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/tAwWnF8e
Shared by Dimitri