Created
April 18, 2018 12:03
-
-
Save johnliu55tw/f13b8b4186af3a86bd5cfaf32bb50df2 to your computer and use it in GitHub Desktop.
Fetch track name and its artist from several track IDs.
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
import time | |
import requests | |
TOKEN = 'Your access token here' | |
def fetch_track(track_id): | |
"""Fetch track data using a track ID.""" | |
resp = requests.get( | |
'https://api.kkbox.com/v1.1/tracks/'+track_id, | |
params={'territory': 'TW'}, | |
headers={'Authorization': 'Bearer ' + TOKEN}) | |
return resp.json() | |
def fetch_tracks_briefly(track_ids): | |
"""Fetch name of tracks and artists from a list of track IDs.""" | |
results = list() | |
for track_id in track_ids: | |
track_info = fetch_track(track_id) | |
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] | |
start = time.time() | |
results = 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