Last active
June 7, 2022 18:09
-
-
Save sansmoraxz/9c3a83bcc81caec24c828bc15b09c9d3 to your computer and use it in GitHub Desktop.
Fetch JSON data from URLs (async) and store in container - python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Install required libraries tqdm, aiohttp | |
# from tqdm import tqdm | |
# import aiohttp | |
import typing | |
async def multiFetchJSON(indices, | |
container: dict = {}, | |
urlFormat: str = '', | |
urlGenerator: typing.Callable = None, | |
returnData: bool = False, | |
**urlParams | |
): | |
async with aiohttp.ClientSession() as session: | |
for id in tqdm(indices): | |
# Don't fetch for the ones already done | |
if id in container.keys(): | |
continue | |
if urlGenerator is not None: | |
url = urlGenerator(id = id) | |
else: | |
url = urlFormat.format(id=id, **urlParams) | |
async with session.get(url) as resp: | |
try: | |
resp.raise_for_status() | |
response_obj = await resp.json() | |
container[id] = response_obj | |
except aiohttp.ClientResponseError as e: | |
print(f'Error: {e.status} for URL: {e.request_info.real_url}') | |
return container if returnData else None |
With callback:
d2 = await multiFetchJSON(
map(str,range(1, 4)), # compliance with JSON standard key type
urlGenerator = lambda id: f'https://pokeapi.co/api/v2/pokemon/{id}',
returnData = True
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample implementation