Skip to content

Instantly share code, notes, and snippets.

@mark-mishyn
Last active September 7, 2021 15:22
Show Gist options
  • Save mark-mishyn/011f15cd2d7b9ea4c42fc922e4386214 to your computer and use it in GitHub Desktop.
Save mark-mishyn/011f15cd2d7b9ea4c42fc922e4386214 to your computer and use it in GitHub Desktop.
Make multiple requests in async and return responses in key-value (key-response) format
import asyncio
import aiohttp
from multidict import CIMultiDictProxy
@dataclass
class AsyncToSyncResponse:
status: int
content: dict
headers: CIMultiDictProxy
reason: str
async def fetch(session, url):
async with session.get(url) as response:
content_dict = await response.json()
return AsyncToSyncResponse(
status=response.status,
content=content_dict,
headers=response.headers,
reason=response.reason
)
def get_responses_async(urls_map: Dict[Hashable, str], headers: dict = None):
"""
Example:
>>> get_responses_async({
>>> 'foo': 'https://example.com/get-profile/biba',
>>> 'bar': 'https://example.com/get-profile/boba'
>>> })
{
'foo': AsyncToSyncResponse(...),
'bar': AsyncToSyncResponse(...)
}
"""
async def send_requests():
async with aiohttp.ClientSession(headers=headers) as session:
return await asyncio.gather(*[fetch(session, url) for url in urls_map.values()])
results = asyncio.run(send_requests())
return dict(zip(urls_map.keys(), results))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment