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 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)