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

Changed cache_handler.py to utilize Python's Context Management Protocol #991

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 7 additions & 8 deletions spotipy/cache_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down