Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
#nft#RugPull#архив
Frosties. История обмана…
В 2022 году случилась первая самая громкая афера Rug pulls NFT — это проект Frosties, на котором инвесторы потеряли 1,3 миллиона долларов😮.
Идея была основана на продаже коллекции мультяшных персонажей, похожих на шарики мороженого 🍨. Создатели проекта заманивали инвесторов бесплатными раздачами, обещали ранний доступ и привилегии в игре. Вокруг Frosties разгорелся огромный ажиотаж, поскольку игра в метавселенной и механизм ставок были обещаны как часть будущей дорожной карты.
🔴Распознать аферу было сложно. У проекта был профессиональный сайт, сообщество насчитывало 40 тыс. активных пользователей.
Каждая NFT Frosties стоила в среднем 0,04 ETH и когда были проданы 8 888 «мороженных» NFT, вкладчики обнаружили, что все соцсети, каналы в Discord, сайт и команда — исчезли 😐.
Инвесторы так и не вернули деньги 😔.
@MirraChannel😎
Hackers Target Crypto Figure for Scam
Hackers compromised World Liberty co-founder Zach Vitkoff's X account to promote a fake Trump meme token. Victims were lured by claims of imminent announcements from President Trump. Despite warnings from Vitkoff, the established token BARRON (market cap over $10B) continues to rise, indicating a scam. Another similar project executed a rug pull, draining liquidity. More details here: ForkLog
#Hacking#Crypto#Trump#MemeToken#Scam#BARRON#Liquidity#RugPull#WorldLiberty
Errol Musk's Token Plans to Raise Millions
Errol Musk aims to raise $150-$200 million through the "Musk It" memecoin, leveraging his family name. Proceeds will support the newly established Musk Institute. Recently, the crypto space has faced various rug pulls linked to projects of the same name. 🪙💰Read more here
#Musk#Memecoin#Crypto#ETFs#USDC#Ethereum#DeFi#Blockchain#Investment#Finance#ElonMusk#Bitcoin#WhaleAlert#RugPull#MuskInstitute#CryptoMarket#DigitalAssets#TokenSale#Cryptocurrency#MarketTrends#VC
Argentina's Opposition Eyes Impeachment Over LIBRA
Argentina's opposition is considering impeachment for President Milei after conflicting support for the LIBRA token. This follows a controversial launch that saw rapid investment and then a significant drop in value, leading to accusations of mismanagement and deception. The situation raises questions about political influence in cryptocurrency projects.
Read more: Reuters
#Argentina#LIBRA#Crypto#Impeachment#Milei#Investment#MarketManipulation#EconomicCrisis#Blockchain#DeFi#RugPull#Politics#Cryptocurrency#TokenLaunch#InsiderTrading#Securities#AI#VC
Argentina Investigates LIBRA Token Misconduct
Argentina's President Javier Milei calls for an investigation into LIBRA token's rug pull, requesting the Anti-Corruption Office's involvement to assess potential misconduct by government members. Findings will be forwarded to the court. Opposition considers impeachment due to the incident. Links: Statement, Watch, Details.
#LIBRA#Crypto#Argentina#investigation#rugpull#president#JavierMilei#impeachment#KIPProtocol#AntiCorruption#fundflow#temporalanalysis#MELANIA#ENRON#Solana#ETF#Bitcoin#adoption#blockchain#corruption#misconduct