Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Spotify 429 (too many requests) API error handling #4370

Merged
merged 12 commits into from
Jun 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions beetsplug/spotify.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,21 @@
Spotify playlist construction.
"""

import re
import json
import base64
import collections
import json
import re
import time
import webbrowser
import collections

import unidecode
import requests
import confuse

import requests
import unidecode
from beets import ui
from beets.autotag.hooks import AlbumInfo, TrackInfo
from beets.plugins import MetadataSourcePlugin, BeetsPlugin
from beets.plugins import BeetsPlugin, MetadataSourcePlugin

DEFAULT_WAITING_TIME = 5


class SpotifyPlugin(MetadataSourcePlugin, BeetsPlugin):
Expand Down Expand Up @@ -164,6 +165,13 @@ def _handle_response(self, request_type, url, params=None):
)
self._authenticate()
return self._handle_response(request_type, url, params=params)
elif response.status_code == 429:
seconds = response.headers.get('Retry-After',
DEFAULT_WAITING_TIME)
self._log.debug('Too many API requests. Retrying after {} \
seconds.', seconds)
time.sleep(int(seconds) + 1)
return self._handle_response(request_type, url, params=params)
else:
raise ui.UserError(
'{} API error:\n{}\nURL:\n{}\nparams:\n{}'.format(
Expand Down Expand Up @@ -577,9 +585,6 @@ def _fetch_info(self, items, write, force):
self._log.debug('Total {} tracks', len(items))

for index, item in enumerate(items, start=1):
# Added sleep to avoid API rate limit
# https://developer.spotify.com/documentation/web-api/guides/rate-limits/
time.sleep(.5)
self._log.info('Processing {}/{} tracks - {} ',
index, len(items), item)
# If we're not forcing re-downloading for all tracks, check
Expand Down
4 changes: 3 additions & 1 deletion docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ New features:

Bug fixes:

* Fix implicit paths OR queries (e.g. ``beet list /path/ , /other-path/``)
* We now respect the Spotify API's rate limiting, which avoids crashing when the API reports code 429 (too many requests).
:bug:`4370`
* Fix implicit paths OR queries (e.g. ``beet list /path/ , /other-path/``)
which have previously been returning the entire library.
:bug:`1865`
* The Discogs release ID is now populated correctly to the discogs_albumid
Expand Down