Added DjangoSessionCacheHandler (#691)

* Added DjangoSessionCacheHandler

Added `DjangoSessionCacheHandler`, a cache handler that stores the token in the session framework provided by Django. Web apps using spotipy with Django can directly use this for cache handling.

* removed whitespaces
This commit is contained in:
Varun Patil 2021-06-19 19:27:36 +05:30 committed by GitHub
parent 85746e4e62
commit d0fc4425f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 1 deletions

View File

@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
* Added `MemoryCacheHandler`, a cache handler that simply stores the token info in memory as an instance attribute of this class. * Added `MemoryCacheHandler`, a cache handler that simply stores the token info in memory as an instance attribute of this class.
* Added `DjangoSessionCacheHandler`, a cache handler that stores the token in the session framework provided by Django. Web apps using spotipy with Django can directly use this for cache handling.
### Fixed ### Fixed

View File

@ -1,4 +1,4 @@
__all__ = ['CacheHandler', 'CacheFileHandler', 'MemoryCacheHandler'] __all__ = ['CacheHandler', 'CacheFileHandler', 'DjangoSessionCacheHandler', 'MemoryCacheHandler']
import errno import errno
import json import json
@ -106,3 +106,35 @@ class MemoryCacheHandler(CacheHandler):
def save_token_to_cache(self, token_info): def save_token_to_cache(self, token_info):
self.token_info = token_info self.token_info = token_info
class DjangoSessionCacheHandler(CacheHandler):
"""
A cache handler that stores the token info in the session framework
provided by Django.
Read more at https://docs.djangoproject.com/en/3.2/topics/http/sessions/
"""
def __init__(self, request):
"""
Parameters:
* request: HttpRequest object provided by Django for every
incoming request
"""
self.request = request
def get_cached_token(self):
token_info = None
try:
token_info = self.request.session['token_info']
except KeyError:
logger.debug("Token not found in the session")
return token_info
def save_token_to_cache(self, token_info):
try:
self.request.session['token_info'] = token_info
except Exception as e:
logger.warning("Error saving token to cache: " + str(e))