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

Make redis dependency optional #869

Merged
merged 5 commits into from
Dec 26, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -475,4 +479,4 @@ Repackaged for saner imports

## [1.0.0] - 2017-04-05

Initial release
Initial release
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,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).
Expand Down
4 changes: 4 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,10 @@ The custom cache handler would need to be a class that inherits from the base
cache handler ``CacheHandler``. The default cache handler ``CacheFileHandler`` is a good example.
An instance of that new class can then be passed as a parameter when
creating ``SpotifyOAuth``, ``SpotifyPKCE`` or ``SpotifyImplicitGrant``.
The following handlers are available and defined in the URL above.
- ``CacheFileHandler``
- ``MemoryCacheHandler``
- ``RedisCacheHandler``

Feel free to contribute new cache handlers to the repo.

Expand Down
8 changes: 7 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
54 changes: 53 additions & 1 deletion spotipy/cache_handler.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
# -*- coding: utf-8 -*-

__all__ = ['CacheHandler', 'CacheFileHandler', 'MemoryCacheHandler']
__all__ = [
'CacheHandler',
'CacheFileHandler',
'MemoryCacheHandler',
'RedisCacheHandler'
]

import errno
import json
import logging
import os
from spotipy.util import CLIENT_CREDS_ENV_VARS
from abc import ABC, abstractmethod
import warnings

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -107,3 +113,49 @@ def get_cached_token(self):

def save_token_to_cache(self, token_info):
self.token_info = token_info


class RedisCacheHandler(CacheHandler):
"""
A cache handler that stores the token info in the 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'

try:
from redis import RedisError
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:
return json.loads(token_info)
except RedisError as e:
logger.warning('Error getting token from cache: ' + str(e))

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:
logger.warning('Error saving token to cache: ' + str(e))