From d0fc4425f71c35993a4050f42ad9bdf891afe864 Mon Sep 17 00:00:00 2001 From: Varun Patil <31964349+varunpatil@users.noreply.github.com> Date: Sat, 19 Jun 2021 19:27:36 +0530 Subject: [PATCH] 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 --- CHANGELOG.md | 1 + spotipy/cache_handler.py | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a3d736..2c8ac5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added * 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 diff --git a/spotipy/cache_handler.py b/spotipy/cache_handler.py index 544316b..eb9e5f2 100644 --- a/spotipy/cache_handler.py +++ b/spotipy/cache_handler.py @@ -1,4 +1,4 @@ -__all__ = ['CacheHandler', 'CacheFileHandler', 'MemoryCacheHandler'] +__all__ = ['CacheHandler', 'CacheFileHandler', 'DjangoSessionCacheHandler', 'MemoryCacheHandler'] import errno import json @@ -106,3 +106,35 @@ class MemoryCacheHandler(CacheHandler): def save_token_to_cache(self, 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))