From f005732a3809bd011f8dbd6327aefe66b29382a6 Mon Sep 17 00:00:00 2001 From: "Andrew J. Hesford" <48421688+ahesford@users.noreply.github.com> Date: Mon, 26 Dec 2022 13:08:04 -0500 Subject: [PATCH] Make redis dependency optional (#869) --- CHANGELOG.md | 4 ++++ README.md | 6 ++++++ setup.py | 8 +++++++- spotipy/cache_handler.py | 16 ++++++++++++++-- 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65fbd62c..3545d70d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ While this is unreleased, please only add v3 features here. Rebasing master onto ### Added * `Scope` - An enum which contains all of the authorization scopes (see [here](https://github.com/plamere/spotipy/issues/652#issuecomment-797461311)). +* Added `RedisCacheHandler`, a cache handler that stores the token info in Redis. +* Added a new parameter to `RedisCacheHandler` to allow custom keys (instead of the default `token_info` key) +* Simplify check for existing token in `RedisCacheHandler` +* Make redis an optional dependency ### Changed diff --git a/README.md b/README.md index 5dd59b2c..9e746c61 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,12 @@ or upgrade pip install spotipy --upgrade ``` +Spotipy includes optional support for caching Spotify access tokens to a Redis server. To use this support, make sure to specify the `redis` extra: + +```bash +pip install spotipy[redis] +``` + ## Quick Start A full set of examples can be found in the [online documentation](http://spotipy.readthedocs.org/) and in the [Spotipy examples directory](https://github.com/plamere/spotipy/tree/master/examples). diff --git a/setup.py b/setup.py index 94d403a1..b2b5c3f7 100644 --- a/setup.py +++ b/setup.py @@ -11,9 +11,15 @@ 'Sphinx>=1.5.2' ] +redis_reqs = [ + "redis>=3.5.3", + "redis<4.0.0;python_version<'3.4'", +] + extra_reqs = { 'doc': doc_reqs, - 'test': test_reqs + 'test': test_reqs, + 'redis': redis_reqs, } setup( diff --git a/spotipy/cache_handler.py b/spotipy/cache_handler.py index 0e871d3f..44aa5300 100644 --- a/spotipy/cache_handler.py +++ b/spotipy/cache_handler.py @@ -12,8 +12,7 @@ import os from spotipy.util import CLIENT_CREDS_ENV_VARS from abc import ABC, abstractmethod - -from redis import RedisError +import warnings logger = logging.getLogger(__name__) @@ -188,8 +187,19 @@ def __init__(self, redis, key=None): self.redis = redis self.key = key if key else 'token_info' + try: + from redis import RedisError # noqa: F401 + except ImportError: + warnings.warn( + 'Error importing module "redis"; ' + 'it is required for RedisCacheHandler', + UserWarning + ) + def get_cached_token(self): token_info = None + from redis import RedisError + try: token_info = self.redis.get(self.key) if token_info: @@ -200,6 +210,8 @@ def get_cached_token(self): return token_info def save_token_to_cache(self, token_info): + from redis import RedisError + try: self.redis.set(self.key, json.dumps(token_info)) except RedisError as e: