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