PageRenderTime 102ms CodeModel.GetById 40ms app.highlight 4ms RepoModel.GetById 56ms app.codeStats 0ms

/django/contrib/sessions/backends/cache.py

https://code.google.com/p/mango-py/
Python | 58 lines | 42 code | 8 blank | 8 comment | 11 complexity | 5db4298ec1cc81a295709bb607e40f21 MD5 | raw file
 1from django.contrib.sessions.backends.base import SessionBase, CreateError
 2from django.core.cache import cache
 3
 4KEY_PREFIX = "django.contrib.sessions.cache"
 5
 6class SessionStore(SessionBase):
 7    """
 8    A cache-based session store.
 9    """
10    def __init__(self, session_key=None):
11        self._cache = cache
12        super(SessionStore, self).__init__(session_key)
13
14    def load(self):
15        session_data = self._cache.get(KEY_PREFIX + self.session_key)
16        if session_data is not None:
17            return session_data
18        self.create()
19        return {}
20
21    def create(self):
22        # Because a cache can fail silently (e.g. memcache), we don't know if
23        # we are failing to create a new session because of a key collision or
24        # because the cache is missing. So we try for a (large) number of times
25        # and then raise an exception. That's the risk you shoulder if using
26        # cache backing.
27        for i in xrange(10000):
28            self.session_key = self._get_new_session_key()
29            try:
30                self.save(must_create=True)
31            except CreateError:
32                continue
33            self.modified = True
34            return
35        raise RuntimeError("Unable to create a new session key.")
36
37    def save(self, must_create=False):
38        if must_create:
39            func = self._cache.add
40        else:
41            func = self._cache.set
42        result = func(KEY_PREFIX + self.session_key, self._get_session(no_load=must_create),
43                self.get_expiry_age())
44        if must_create and not result:
45            raise CreateError
46
47    def exists(self, session_key):
48        if self._cache.has_key(KEY_PREFIX + session_key):
49            return True
50        return False
51
52    def delete(self, session_key=None):
53        if session_key is None:
54            if self._session_key is None:
55                return
56            session_key = self._session_key
57        self._cache.delete(KEY_PREFIX + session_key)
58