2008-08-14 11:57:18 +08:00
|
|
|
from django.contrib.sessions.backends.base import SessionBase, CreateError
|
2007-09-16 05:29:14 +08:00
|
|
|
from django.core.cache import cache
|
|
|
|
|
2011-09-10 08:46:48 +08:00
|
|
|
KEY_PREFIX = "django.contrib.sessions.cache"
|
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
class SessionStore(SessionBase):
|
|
|
|
"""
|
2008-06-08 04:28:06 +08:00
|
|
|
A cache-based session store.
|
2007-09-16 05:29:14 +08:00
|
|
|
"""
|
|
|
|
def __init__(self, session_key=None):
|
|
|
|
self._cache = cache
|
|
|
|
super(SessionStore, self).__init__(session_key)
|
2008-06-08 04:28:06 +08:00
|
|
|
|
2007-09-16 05:29:14 +08:00
|
|
|
def load(self):
|
2011-09-10 08:46:48 +08:00
|
|
|
session_data = self._cache.get(KEY_PREFIX + self.session_key)
|
2008-08-14 11:57:18 +08:00
|
|
|
if session_data is not None:
|
|
|
|
return session_data
|
|
|
|
self.create()
|
2008-08-16 23:54:36 +08:00
|
|
|
return {}
|
2007-09-16 05:29:14 +08:00
|
|
|
|
2008-08-14 11:57:18 +08:00
|
|
|
def create(self):
|
2008-08-27 16:58:51 +08:00
|
|
|
# Because a cache can fail silently (e.g. memcache), we don't know if
|
|
|
|
# we are failing to create a new session because of a key collision or
|
|
|
|
# because the cache is missing. So we try for a (large) number of times
|
|
|
|
# and then raise an exception. That's the risk you shoulder if using
|
|
|
|
# cache backing.
|
|
|
|
for i in xrange(10000):
|
2008-08-14 11:57:18 +08:00
|
|
|
self.session_key = self._get_new_session_key()
|
|
|
|
try:
|
|
|
|
self.save(must_create=True)
|
|
|
|
except CreateError:
|
|
|
|
continue
|
|
|
|
self.modified = True
|
|
|
|
return
|
2008-08-27 16:58:51 +08:00
|
|
|
raise RuntimeError("Unable to create a new session key.")
|
2008-08-14 11:57:18 +08:00
|
|
|
|
|
|
|
def save(self, must_create=False):
|
|
|
|
if must_create:
|
|
|
|
func = self._cache.add
|
|
|
|
else:
|
|
|
|
func = self._cache.set
|
2011-09-10 08:46:48 +08:00
|
|
|
result = func(KEY_PREFIX + self.session_key, self._get_session(no_load=must_create),
|
2008-08-15 03:43:08 +08:00
|
|
|
self.get_expiry_age())
|
2008-08-14 11:57:18 +08:00
|
|
|
if must_create and not result:
|
|
|
|
raise CreateError
|
2007-09-16 05:29:14 +08:00
|
|
|
|
|
|
|
def exists(self, session_key):
|
2011-09-10 08:46:48 +08:00
|
|
|
return (KEY_PREFIX + session_key) in self._cache
|
2008-06-08 04:28:06 +08:00
|
|
|
|
2008-08-14 11:57:46 +08:00
|
|
|
def delete(self, session_key=None):
|
|
|
|
if session_key is None:
|
2008-08-15 22:59:11 +08:00
|
|
|
if self._session_key is None:
|
|
|
|
return
|
2008-08-14 11:57:46 +08:00
|
|
|
session_key = self._session_key
|
2011-09-10 08:46:48 +08:00
|
|
|
self._cache.delete(KEY_PREFIX + session_key)
|
2008-08-14 11:57:18 +08:00
|
|
|
|