diff --git a/common/update_playlists.py b/common/update_playlists.py index b721ad4..5da30b5 100644 --- a/common/update_playlists.py +++ b/common/update_playlists.py @@ -18,13 +18,23 @@ class PlaylistUpdater: def _update_tracks(self): self._tracks = [] - headers = { 'Authorization': f"Bearer {self._auth_token}" } rnext = f"{self._spotify_api_endpoint}/me/tracks?limit=50" while rnext is not None: - r = rq.get(rnext, headers = headers).json() + r = self._fetch(rnext); self._tracks += r['items'] rnext = r['next'] + def _fetch(self, url): + headers = { 'Authorization': f"Bearer {self._auth_token}" } + while True: + r = rq.get(f"{url}", headers=headers) + if 200 <= r.status_code <= 299: + return r.json() + # slow down if spotify is applying rate limiting + if r.status_code == 429: + time.sleep(30) + # don't try again in a crazy fast loop to avoid rate limits + time.sleep(1) def update_playlist(self, playlist_id): pltracks = [] @@ -34,12 +44,12 @@ class PlaylistUpdater: headers = { 'Authorization': f"Bearer {self._auth_token}" } added_at_dict = {} - r = rq.get(f"{self._spotify_api_endpoint}/playlists/{playlist_id}?fields=tracks,snapshot_id", headers = headers).json() + r = self._fetch(f"{self._spotify_api_endpoint}/playlists/{playlist_id}?fields=tracks,snapshot_id") snapshot_id = r['snapshot_id'] pltracks = [t['track']['id'] for t in r['tracks']['items']] rnext = r['tracks']['next'] while rnext is not None: - r = rq.get(rnext, headers = headers).json() + r = self._fetch(rnext) for track in r['items']: pltracks.append(track['track']['id']) rnext = r['next']