Python
Асинхронные HTTP-запросы на aiohttp
Сотни параллельных запросов в одном потоке; семафор ограничивает нагрузку на сервер.
Код
import asyncio
import aiohttp
async def fetch(session, url, semaphore):
async with semaphore:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=15)) as resp:
return url, resp.status, await resp.text()
async def fetch_all(urls, limit=10):
semaphore = asyncio.Semaphore(limit)
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url, semaphore) for url in urls]
return await asyncio.gather(*tasks, return_exceptions=True)
urls = [f"https://httpbin.org/anything/{i}" for i in range(20)]
for result in asyncio.run(fetch_all(urls)):
if isinstance(result, Exception):
print("Ошибка:", result)
else:
print(result[1], result[0])