Concurrency
Difference Between Asynchronous and Multi-Threading Programming
Asyncio
import asyncio
import aiohttp
async def fetch(session, url, headers=None, params=None):
"""
Fetch data from a single API endpoint asynchronously.
"""
try:
async with session.get(url, headers=headers, params=params) as response:
response.raise_for_status()
return await response.json()
except aiohttp.ClientError as e:
print(f"Request to {url} failed: {e}")
return None
async def fetch_all(urls, headers=None, params=None):
"""
Fetch data from multiple API endpoints concurrently.
"""
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url, headers, params) for url in urls]
return await asyncio.gather(*tasks)
# 🔧 Example usage
if __name__ == "__main__":
urls = [
"https://api.github.com/repos/python/cpython",
"https://api.github.com/repos/django/django",
"https://api.github.com/repos/pallets/flask"
]
results = asyncio.run(fetch_all(urls))
for i, result in enumerate(results):
if result:
print(f"{urls[i]} ➜ {result.get('description')}")
Concurrent.futures
Reference
Last updated