Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🐱 Выжиматор кошачьего корма – экологично, чисто и удобно!
Это удобное устройство поможет оставить руки чистыми от влажного корма и сделает кормление кошек проще! Без отходов, легко моется, быстро печатается на 3D-принтере!
🔗Скачать:Printables
#️⃣ Категория:#Pets@anzar3d
🖨3D модели для печати | 3D Маркетплейс | Max
Hamster Kombat Announcement: Celebrate International Hamster Day!
#hamster#pets
Hamster Kombat Announcement highlights International Hamster Day on April 12, a day to celebrate these adorable pets with treats and affection. Join in the tradition and make your hamster feel extra special.
Source: link
@tonlines
Furry friends receive blessings at Peru monastery
Animal lovers in Lima, Peru, had their pets blessed during a special mass for their four-legged friends at the Saint Francis Monastery.
#News#Reuters#Pets#Peru
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Nest Veterinary Secures $700K Funding
Nest Veterinary has successfully raised $700,000 in funding to support its innovative platform that enables users to create and manage customized wellness plans for pets. This funding round took place on December 16, 2024. For more details, visit Nest Veterinary.
#Veterinary#Funding#WellnessPlans#Pets#Startup
Russia Proposes Unified Pet Registry
The St. Petersburg Legislative Assembly has initiated a bill to create a unified registry for pets, requiring mandatory registration and tagging. The draft law is now in the State Duma. Owners must register their animals, aiding quick recovery if lost and identifying owners in case of damage. The government will approve which animals must be registered. A similar proposal led by deputy Nina Ostanina previously gained committee support.
#Russia#pets#registry#law#StateDuma
The main news of Russia and the world ishere.
Slideshow: Drive-through pet blessing
Hundreds of animal lovers in the Philippines had their pets blessed via a drive-through ceremony.
#News#Reuters#Drivethrough#pets#blessing#slideshow
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Jumping spiders are small spiders in the Salticidae family. They have four pairs of eyes, with large front eyes for hunting and navigation. They do not build webs to catch prey. They hunt by stalking and leaping on insects. They use silk as a safety line when they jump. Some species are kept as pets and are easy to care for.
🕷️🌿🎯
[Read more]
@googlefactss
#Spiders#JumpingSpider#Salticidae#Nature#Pets