Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
goldendict-ng
下一代 GoldenDict。一款功能丰富的开源词典查找程序,支持多种词典格式和在线词典。
https://xiaoyifang.github.io/goldendict-ng/
https://forum.freemdict.com/
https://github.com/lrorpilla/jidoujisho
Japanese-Chinese dictionaries.
https://cloud.freemdict.com/index.php/s/pgKcDcbSDTCzXCs?path=%2FJAPANESE%2FJpn-Chi
recommend using that add-on for anki:
https://ankiweb.net/shared/info/1344485230
the complete guide of how to configure goldendict-ng for Japanese :
https://tatsumoto-ren.github.io/blog/setting-up-goldendict.html
create anki cards from anime
https://github.com/Ajatt-Tools/mpvacious
#dict
https://github.com/blissnd/easyxls
Convert any #spreadsheet into a Python internal #dict/#array data structure, for easy processing. Can also handle pivot tables.
For pivot table usage, header_row_start & header_col_start need to be set equal to the top left corner of the pivot table => header_row_start=8, header_col_start='c' in the included example.
Column IDs must always be lowercase chars in quotes, e.g. 'a'.
👑New Meme Contest
👑
💰Reward : 100 USDT For Top 10 People🤑
👑Contest Link : Meme Contest
⭐Steps to take Part
⭐ Follow @dict00
⭐ Like RT Quite this tweet+comments @ 3 friends
⭐ Add your #DICT meme to the comments below
⭐ Must join Telegram Channel
⭐ Send proof in Telegram group with retweet link
#MemeContest#100USDT#USDT#giveaway
🔔Note: Please do your own research (DYOR) before joining to any project.Don't send any fee or penny without doing own research
✈️Business:@ProjectPromoters✅
@lingvanexbot
Qué puede hacer este bot?
Este es un bot traductor de alta calidad basada en redes neuronales para más de 50 idiomas.
➕ Traducir cualquier texto o palabras
➕ Convertir texto a voz
➕ Dar definiciones para cualquier palabra
➕ Diccionario
➕ Buscar por ejemplos de traducciones
Idioma: Múltiple
(visto en @BotsGram_cu)
#linguistic, #translate, #define, #dictionary, #dict, #text2speech, #speech, #examples, #sentence, #words