from django.conf import settings 
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import cache 
 
class SessionStore(DBStore): 
    """ 
    Implements cached database session store 
    """ 
    def __init__(self, session_key=None): 
        super(SessionStore, self).__init__(session_key) 
 
    def _get_cache_key(self): 
        return 'django_session_backend_cache_%s' % (self.session_key) 
     
    def load(self):
        cache_key = self._get_cache_key()
        data = cache.get(cache_key, None) 
        if data is None: 
            data = super(SessionStore, self).load()
            cache.set(cache_key, data, settings.SESSION_COOKIE_AGE) 
        return data 
             
    def exists(self, session_key): 
        return super(SessionStore, self).exists(session_key)
             
    def save(self, must_create=False): 
        super(SessionStore, self).save(must_create)
        cache.set(self._get_cache_key(), self._session, settings.SESSION_COOKIE_AGE) 
     
    def delete(self, session_key): 
        super(SessionStore, self).delete(session_key)
        cache.delete(self._get_cache_key())
    
    def flush(self):
        """
        Removes the current session data from the database and regenerates the
        key.
        """
        self.clear()
        self.delete(self.session_key)
        self.create()