Skip to content

Commit

Permalink
use newer string formatters (https://pyformat.info)
Browse files Browse the repository at this point in the history
  • Loading branch information
dieser-niko authored Oct 6, 2024
1 parent d9da5af commit 4de3001
Show file tree
Hide file tree
Showing 13 changed files with 50 additions and 60 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Add your changes below.
- Added custom `urllib3.Retry` class for printing a warning when a rate/request limit is reached.
- Added `personalized_playlist.py`, `track_recommendations.py`, and `audio_features_analysis.py` to `/examples`.
- Discord badge in README
- Use newer string formatters (https://pyformat.info)

### Fixed
- Audiobook integration tests
Expand Down
2 changes: 1 addition & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ class SpotifyClientCredentials that can be used to authenticate requests like so
playlists = sp.user_playlists('spotify')
while playlists:
for i, playlist in enumerate(playlists['items']):
print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'], playlist['name']))
print("{:4d} {} {}".format(i + 1 + playlists['offset'], playlist['uri'], playlist['name']))
if playlists['next']:
playlists = sp.next(playlists)
else:
Expand Down
4 changes: 2 additions & 2 deletions examples/artist_albums.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def show_artist_albums(artist):
for album in albums:
name = album['name']
if name not in seen:
logger.info('ALBUM: %s', name)
logger.info('ALBUM: {name}')
seen.add(name)


Expand All @@ -48,7 +48,7 @@ def main():
if artist:
show_artist_albums(artist)
else:
logger.error("Can't find artist: %s", artist)
logger.error(f"Can't find artist: {artist}")


if __name__ == '__main__':
Expand Down
12 changes: 6 additions & 6 deletions examples/artist_discography.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def show_album_tracks(album):
results = sp.next(results)
tracks.extend(results['items'])
for i, track in enumerate(tracks):
logger.info('%s. %s', i + 1, track['name'])
logger.info(f'{i + 1}. {track["name"]}')


def show_artist_albums(artist):
Expand All @@ -44,21 +44,21 @@ def show_artist_albums(artist):
while results['next']:
results = sp.next(results)
albums.extend(results['items'])
logger.info('Total albums: %s', len(albums))
logger.info(f'Total albums: {len(albums)}')
unique = set() # skip duplicate albums
for album in albums:
name = album['name'].lower()
if name not in unique:
logger.info('ALBUM: %s', name)
logger.info(f'ALBUM: {name}')
unique.add(name)
show_album_tracks(album)


def show_artist(artist):
logger.info('====%s====', artist['name'])
logger.info('Popularity: %s', artist['popularity'])
logger.info(f'===={artist["name"]}====')
logger.info(f'Popularity: {artist["popularity"]}')
if len(artist['genres']) > 0:
logger.info('Genres: %s', ','.join(artist['genres']))
logger.info('Genres: {}'.format(','.join(artist['genres'])))


def main():
Expand Down
3 changes: 1 addition & 2 deletions examples/artist_recommendations.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ def get_artist(name):
def show_recommendations_for_artist(artist):
results = sp.recommendations(seed_artists=[artist['id']])
for track in results['tracks']:
logger.info('Recommendation: %s - %s', track['name'],
track['artists'][0]['name'])
logger.info(f'Recommendation: {track["name"]} - {track["artists"][0]["name"]}')


def main():
Expand Down
2 changes: 1 addition & 1 deletion examples/my_playlists.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@

results = sp.current_user_playlists(limit=50)
for i, item in enumerate(results['items']):
print("%d %s" % (i, item['name']))
print(f"{i} {item['name']}")
2 changes: 1 addition & 1 deletion examples/show_my_saved_tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
def show_tracks(results):
for item in results['items']:
track = item['track']
print("%32.32s %s" % (track['artists'][0]['name'], track['name']))
print(f"{track['artists'][0]['name']:>32.32} {track['name']}")


sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
Expand Down
4 changes: 1 addition & 3 deletions examples/user_playlists_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
def show_tracks(results):
for i, item in enumerate(results['items']):
track = item['track']
print(
" %d %32.32s %s" %
(i, track['artists'][0]['name'], track['name']))
print(f" {i} {track['artists'][0]['name']:>32.32} {track['name']}")


if __name__ == '__main__':
Expand Down
8 changes: 1 addition & 7 deletions examples/user_public_playlists.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,7 @@

while playlists:
for i, playlist in enumerate(playlists['items']):
print(
"%4d %s %s" %
(i +
1 +
playlists['offset'],
playlist['uri'],
playlist['name']))
print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}")
if playlists['next']:
playlists = sp.next(playlists)
else:
Expand Down
7 changes: 3 additions & 4 deletions spotipy/cache_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ def get_cached_token(self):

except OSError as error:
if error.errno == errno.ENOENT:
logger.debug("cache does not exist at: %s", self.cache_path)
logger.debug(f"cache does not exist at: {self.cache_path}")
else:
logger.warning("Couldn't read cache at: %s", self.cache_path)
logger.warning(f"Couldn't read cache at: {self.cache_path}")

return token_info

Expand All @@ -95,8 +95,7 @@ def save_token_to_cache(self, token_info):
f.write(json.dumps(token_info, cls=self.encoder_cls))
f.close()
except OSError:
logger.warning('Couldn\'t write token to cache at: %s',
self.cache_path)
logger.warning(f"Couldn't write token to cache at: {self.cache_path}")


class MemoryCacheHandler(CacheHandler):
Expand Down
11 changes: 6 additions & 5 deletions spotipy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@ def _internal_call(self, method, url, payload, params):
if self.language is not None:
headers["Accept-Language"] = self.language

logger.debug('Sending %s to %s with Params: %s Headers: %s and Body: %r ',
method, url, args.get("params"), headers, args.get('data'))
logger.debug('Sending {} to {} with Params: {} Headers: {} and Body: {!r} '.format(
method, url, args.get("params"), headers, args.get('data')))

try:
response = self._session.request(
Expand All @@ -290,8 +290,9 @@ def _internal_call(self, method, url, payload, params):
reason = None

logger.error(
'HTTP Error for %s to %s with Params: %s returned %s due to %s',
method, url, args.get("params"), response.status_code, msg
'HTTP Error for {} to {} with Params: {} returned {} due to {}'.format(
method, url, args.get("params"), response.status_code, msg
)
)

raise SpotifyException(
Expand All @@ -317,7 +318,7 @@ def _internal_call(self, method, url, payload, params):
except ValueError:
results = None

logger.debug('RESULTS: %s', results)
logger.debug(f'RESULTS: {results}')
return results

def _get(self, url, args=None, payload=None, **kwargs):
Expand Down
50 changes: 24 additions & 26 deletions spotipy/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,8 @@ def _request_access_token(self):
)

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
"sending POST request to {} with Headers: {} and Body: {!r}".format(
self.OAUTH_TOKEN_URL, headers, payload)
)

try:
Expand Down Expand Up @@ -423,9 +423,9 @@ def _open_auth_url(self):
auth_url = self.get_authorize_url()
try:
webbrowser.open(auth_url)
logger.info("Opened %s in your browser", auth_url)
logger.info(f"Opened {auth_url} in your browser")
except webbrowser.Error:
logger.error("Please navigate here: %s", auth_url)
logger.error(f"Please navigate here: {auth_url}")

def _get_auth_response_interactive(self, open_browser=False):
if open_browser:
Expand All @@ -434,8 +434,8 @@ def _get_auth_response_interactive(self, open_browser=False):
else:
url = self.get_authorize_url()
prompt = (
"Go to the following URL: {}\n"
"Enter the URL you were redirected to: ".format(url)
f"Go to the following URL: {url}\n"
"Enter the URL you were redirected to: "
)
response = self._get_user_input(prompt)
state, code = SpotifyOAuth.parse_auth_response_url(response)
Expand Down Expand Up @@ -479,12 +479,11 @@ def get_auth_response(self, open_browser=None):
if redirect_port:
return self._get_auth_response_local_server(redirect_port)
else:
logger.warning('Using `%s` as redirect URI without a port. '
'Specify a port (e.g. `%s:8080`) to allow '
logger.warning(f'Using `{redirect_host}` as redirect URI without a port. '
f'Specify a port (e.g. `{redirect_host}:8080`) to allow '
'automatic retrieval of authentication code '
'instead of having to copy and paste '
'the URL your browser is redirected to.',
redirect_host, redirect_host)
'the URL your browser is redirected to.')

return self._get_auth_response_interactive(open_browser=open_browser)

Expand Down Expand Up @@ -533,8 +532,8 @@ def get_access_token(self, code=None, as_dict=True, check_cache=True):
headers = self._make_authorization_headers()

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
"sending POST request to {} with Headers: {} and Body: {!r}".format(
self.OAUTH_TOKEN_URL, headers, payload)
)

try:
Expand Down Expand Up @@ -563,8 +562,8 @@ def refresh_access_token(self, refresh_token):
headers = self._make_authorization_headers()

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
"sending POST request to {} with Headers: {} and Body: {!r}".format(
self.OAUTH_TOKEN_URL, headers, payload)
)

try:
Expand Down Expand Up @@ -755,9 +754,9 @@ def _open_auth_url(self, state=None):
auth_url = self.get_authorize_url(state)
try:
webbrowser.open(auth_url)
logger.info("Opened %s in your browser", auth_url)
logger.info(f"Opened {auth_url} in your browser")
except webbrowser.Error:
logger.error("Please navigate here: %s", auth_url)
logger.error(f"Please navigate here: {auth_url}")

def _get_auth_response(self, open_browser=None):
logger.info('User authentication requires interaction with your '
Expand All @@ -781,12 +780,11 @@ def _get_auth_response(self, open_browser=None):
if redirect_port:
return self._get_auth_response_local_server(redirect_port)
else:
logger.warning('Using `%s` as redirect URI without a port. '
'Specify a port (e.g. `%s:8080`) to allow '
logger.warning(f'Using `{redirect_host}` as redirect URI without a port. '
f'Specify a port (e.g. `{redirect_host}:8080`) to allow '
'automatic retrieval of authentication code '
'instead of having to copy and paste '
'the URL your browser is redirected to.',
redirect_host, redirect_host)
'the URL your browser is redirected to.')
return self._get_auth_response_interactive(open_browser=open_browser)

def _get_auth_response_local_server(self, redirect_port):
Expand Down Expand Up @@ -890,8 +888,8 @@ def get_access_token(self, code=None, check_cache=True):
headers = {"Content-Type": "application/x-www-form-urlencoded"}

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
"sending POST request to {} with Headers: {} and Body: {!r}".format(
self.OAUTH_TOKEN_URL, headers, payload)
)

try:
Expand Down Expand Up @@ -921,8 +919,8 @@ def refresh_access_token(self, refresh_token):
headers = {"Content-Type": "application/x-www-form-urlencoded"}

logger.debug(
"sending POST request to %s with Headers: %s and Body: %r",
self.OAUTH_TOKEN_URL, headers, payload
"sending POST request to {} with Headers: {} and Body: {!r}".format(
self.OAUTH_TOKEN_URL, headers, payload)
)

try:
Expand Down Expand Up @@ -1174,9 +1172,9 @@ def _open_auth_url(self, state=None):
auth_url = self.get_authorize_url(state)
try:
webbrowser.open(auth_url)
logger.info("Opened %s in your browser", auth_url)
logger.info(f"Opened {auth_url} in your browser")
except webbrowser.Error:
logger.error("Please navigate here: %s", auth_url)
logger.error(f"Please navigate here: {auth_url}")

def get_auth_response(self, state=None):
""" Gets a new auth **token** with user interaction """
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/user_endpoints/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ def test_add_to_queue(self, mock_post):
self.spotify.add_to_queue(test_uri)

# Check if the correct endpoint is called
endpoint = "me/player/queue?uri=%s" % test_uri
endpoint = f"me/player/queue?uri={test_uri}"
mock_post.assert_called_with(endpoint)

def test_add_to_queue_with_device_id(self, mock_post):
Expand All @@ -597,5 +597,5 @@ def test_add_to_queue_with_device_id(self, mock_post):
self.spotify.add_to_queue(test_uri, device_id=device_id)

# Check if the correct endpoint is called
endpoint = "me/player/queue?uri=%s&device_id=%s" % (test_uri, device_id)
endpoint = f"me/player/queue?uri={test_url}&device_id={device_id}"
mock_post.assert_called_with(endpoint)

0 comments on commit 4de3001

Please sign in to comment.