Skip to content

Commit

Permalink
Allow to set custom key in RedisCacheHandler (spotipy-dev#761)
Browse files Browse the repository at this point in the history
* Allow to set custom key in RedisCacheHandler

* Update CHANGELOG.md

* Check for the existence of the key
  • Loading branch information
ENT8R authored and IdmFoundInHim committed Dec 23, 2021
1 parent 10a1e00 commit b42034f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
* Added `RedisCacheHandler`, a cache handler that stores the token info in Redis.
* Changed URI handling in `client.Spotify._get_id()` to remove qureies if provided by error.
* Added a new parameter to `RedisCacheHandler` to allow custom keys (instead of the default `token_info` key)

## [2.19.0] - 2021-08-12

Expand Down
10 changes: 7 additions & 3 deletions spotipy/cache_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,25 +152,29 @@ class RedisCacheHandler(CacheHandler):
A cache handler that stores the token info in the Redis.
"""

def __init__(self, redis):
def __init__(self, redis, key=None):
"""
Parameters:
* redis: Redis object provided by redis-py library
(https://github.com/redis/redis-py)
* key: May be supplied, will otherwise be generated
(takes precedence over `token_info`)
"""
self.redis = redis
self.key = key if key else 'token_info'

def get_cached_token(self):
token_info = None
try:
token_info = json.loads(self.redis.get('token_info'))
if self.redis.exists(self.key):
token_info = json.loads(self.redis.get(self.key))
except RedisError as e:
logger.warning('Error getting token from cache: ' + str(e))

return token_info

def save_token_to_cache(self, token_info):
try:
self.redis.set('token_info', json.dumps(token_info))
self.redis.set(self.key, json.dumps(token_info))
except RedisError as e:
logger.warning('Error saving token to cache: ' + str(e))

0 comments on commit b42034f

Please sign in to comment.