Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
¡Ya llegó la hora de El Doble!
Primero que todo escucha nuestra entrada distintiva y no olvides comentarnos qué te pareció. 💬
📣 En este episodio conversaremos con dos estudiantes fundadoras de #Avizor, un proyecto de comunicación que apuesta por visibilizar tabúes, problemáticas sociales y de género.
🗣 El Anteproyecto del Código de las Familias y sus temas más sensibles también entrarán a debate.
Sin más, ¡disfruta tu ración! 😉
⬇️ (#Descarga gratis desde esta nube con la contraseña ElDoble3)
¿Que puede hacer este bot?
@ytsongdl_bot
Descarga música enviando el nombre o el enlace de una canción
Idioma: inglés
(Visto en @botsgram_cu)
#música#descarga
¿Que puede hacer este bot?
@freemusicprobot
El bot encontrará música por su solicitud, por el nombre de la canción o artista.
También funciona inline.
Idiomas: inglés, ruso
(Visto en @botsgram_cu)
#música#descarga
¿Que puede hacer este bot?
@WebSnatchBot
Este bot le permite descargar videos de alta calidad de más de mil sitios compatibles. ¡Simplemente envíele un enlace de video y observe cómo sucede la magia!
Idioma: inglés
(Visto en @botsgram_cu)
#videos#descarga
¿Que puede hacer este bot?
@DirectFileLinkBot
Este bot genera un enlace de descarga directa de archivos de Telegram.
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descarga
¿Que puede hacer este bot?
@FileSharerRobot
Este bot puede ayudarlo a crear un enlace para compartir archivos de Telegram
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descarga
¿Que puede hacer este bot?
@Qualyuploadbot
Envíe cualquier enlace URL de descarga directa, y el bot subirá a telegram como archivo / video
Idiomas: inglés
(visto en @botsgram_cu)
#enlaces#descarga
¿Que puede hacer este bot?
@torrentDxBoT
Este bot te ayudará a buscar y descargar contenido de torrent
Idiomas: inglés
(Visto en @botsgram_cu)
#torrent#descarga
¿Que puede hacer este bot?
@leoanydlbot
Con este bot puedes descargar videos de varias fuentes
Idiomas: inglés
(Visto en @botsgram_cu)
#enlaces#descarga#videos
¿Que puede hacer este bot?
@TGYouTube_Bot
Este bot puede convertir el enlace de Youtube a video / archivo y MP3 con soporte de miniaturas personalizadas
Idiomas: inglés
(Visto en @botsgram_cu)
#descarga#enlaces#youtube
¿Que puede hacer este bot?
@GetImageUrlBot
Este bot cargará una foto en un sitio y le devolverá el enlace listo para enviar desde cualquier lugar
Idiomas: italiano
(visto en @botsgram_cu)
#fotos#enlaces#descarga
¿Que puede hacer este bot?
@TiktokDl_Robot
Descargue videos originales de tiktok fácilmente.
Idiomas: inglés
(visto en @botsgram_cu)
#tiktok#descarga#videos