Skip to content

Instantly share code, notes, and snippets.

@johnliu55tw
Created April 18, 2018 13:20
Show Gist options
  • Save johnliu55tw/d0d58fff6251d2999d6b9bd1ef43dbf7 to your computer and use it in GitHub Desktop.
Save johnliu55tw/d0d58fff6251d2999d6b9bd1ef43dbf7 to your computer and use it in GitHub Desktop.
Fetch track name and its artist from several track IDs using asyncio.
import time
import asyncio
import aiohttp
TOKEN = 'Your access token here'
async def fetch_track(track_id):
"""Async. fetch track data using a track ID."""
async with aiohttp.request('GET',
'https://api.kkbox.com/v1.1/tracks/'+track_id,
params={'territory': 'TW'},
headers={'Authorization': 'Bearer ' + TOKEN}) as resp:
return await resp.json()
async def fetch_tracks_briefly(track_ids):
"""Async. fetch name of tracks and artists from a list of track IDs."""
results = list()
futures = asyncio.as_completed(
[fetch_track(track_id) for track_id in track_ids])
for future in futures:
track_info = await future
results.append((
track_info['id'],
track_info['name'],
track_info['album']['artist']['name']))
return results
def main():
"""Do the fetching and calculate the time."""
with open('20_tracks.txt', 'r') as f:
track_ids = [track_id.strip() for track_id in f]
loop = asyncio.get_event_loop()
start = time.time()
results = loop.run_until_complete(fetch_tracks_briefly(track_ids))
end = time.time()
print('Fetched {} tracks in {:.3f} seconds.'.format(
len(results), end-start))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment