From 87e4c65ca41cd9d80470ab84b1fdc3a98d4f12c0 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 12 Jun 2023 14:11:20 -0400 Subject: [PATCH 1/2] Changed CacheHandler methods get_cached_token and save_token_to_cache to utilize pythons context management protocol to open and close files, instead of opening and closing manually. More information specified in the pull request. --- spotipy/cache_handler.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/spotipy/cache_handler.py b/spotipy/cache_handler.py index 9a6d703b..2011a919 100644 --- a/spotipy/cache_handler.py +++ b/spotipy/cache_handler.py @@ -75,24 +75,23 @@ def get_cached_token(self): token_info = None try: - f = open(self.cache_path) - token_info_string = f.read() - f.close() - token_info = json.loads(token_info_string) - + with open(self.cache_path) as f: + token_info_string = f.read() + token_info = json.loads(token_info_string) except IOError as error: if error.errno == errno.ENOENT: logger.debug("cache does not exist at: %s", self.cache_path) else: logger.warning("Couldn't read cache at: %s", self.cache_path) + except json.JSONDecodeError: + logger.warning("Couldn't decode JSON from cache at: %s", self.cache_path) return token_info def save_token_to_cache(self, token_info): try: - f = open(self.cache_path, "w") - f.write(json.dumps(token_info, cls=self.encoder_cls)) - f.close() + with open(self.cache_path, "w") as f: + f.write(json.dumps(token_info, cls=self.encoder_cls)) except IOError: logger.warning('Couldn\'t write token to cache at: %s', self.cache_path) From cf9d89de7f5010be5a8920c0f5ba1c99c9a98701 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 12 Jun 2023 14:35:09 -0400 Subject: [PATCH 2/2] Updated changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f69d8fc3..67a05006 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased ### Changed +- Updated get_cached_token and save_token_to_cache methods to utilize Python's Context Management Protocol +- Added except clause to get_cached_token method to handle json decode errors + - Changes the YouTube video link for authentication tutorial (the old video was in low definition, the new one is in high definition) - Updated links to Spotify in documentation