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
|
|
|
|
|
|
|
|
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):
|
|
|
|
session_data = self._cache.get(self.session_key)
|
2008-08-14 11:57:18 +08:00
|
|
|
if session_data is not None:
|
|
|
|
return session_data
|
|
|
|
self.create()
|
2007-09-16 05:29:14 +08:00
|
|
|
|
2008-08-14 11:57:18 +08:00
|
|
|
def create(self):
|
|
|
|
while True:
|
|
|
|
self.session_key = self._get_new_session_key()
|
|
|
|
try:
|
|
|
|
self.save(must_create=True)
|
|
|
|
except CreateError:
|
|
|
|
continue
|
|
|
|
self.modified = True
|
|
|
|
return
|
|
|
|
|
|
|
|
def save(self, must_create=False):
|
|
|
|
if must_create:
|
|
|
|
func = self._cache.add
|
|
|
|
else:
|
|
|
|
func = self._cache.set
|
2008-08-15 03:43:08 +08:00
|
|
|
result = func(self.session_key, self._get_session(no_load=must_create),
|
|
|
|
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):
|
|
|
|
if self._cache.get(session_key):
|
|
|
|
return True
|
|
|
|
return False
|
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:
|
|
|
|
session_key = self._session_key
|
2008-06-23 13:08:07 +08:00
|
|
|
self._cache.delete(session_key)
|
2008-08-14 11:57:18 +08:00
|
|
|
|