1 | from django.conf import settings
|
---|
2 | from django.contrib.sessions.backends.db import SessionStore as DBStore
|
---|
3 | from django.core.cache import cache
|
---|
4 |
|
---|
5 | class SessionStore(DBStore):
|
---|
6 | """
|
---|
7 | Implements cached database session store
|
---|
8 | """
|
---|
9 | def __init__(self, session_key=None):
|
---|
10 | super(SessionStore, self).__init__(session_key)
|
---|
11 |
|
---|
12 | def _get_cache_key(self):
|
---|
13 | return 'django_session_backend_cache_%s' % (self.session_key)
|
---|
14 |
|
---|
15 | def load(self):
|
---|
16 | cache_key = self._get_cache_key()
|
---|
17 | data = cache.get(cache_key, None)
|
---|
18 | if data is None:
|
---|
19 | data = super(SessionStore, self).load()
|
---|
20 | cache.set(cache_key, data, settings.SESSION_COOKIE_AGE)
|
---|
21 | return data
|
---|
22 |
|
---|
23 | def exists(self, session_key):
|
---|
24 | return super(SessionStore, self).exists(session_key)
|
---|
25 |
|
---|
26 | def save(self, must_create=False):
|
---|
27 | super(SessionStore, self).save(must_create)
|
---|
28 | cache.set(self._get_cache_key(), self._session, settings.SESSION_COOKIE_AGE)
|
---|
29 |
|
---|
30 | def delete(self, session_key):
|
---|
31 | super(SessionStore, self).delete(session_key)
|
---|
32 | cache.delete(self._get_cache_key())
|
---|
33 |
|
---|
34 | def flush(self):
|
---|
35 | """
|
---|
36 | Removes the current session data from the database and regenerates the
|
---|
37 | key.
|
---|
38 | """
|
---|
39 | self.clear()
|
---|
40 | self.delete(self.session_key)
|
---|
41 | self.create()
|
---|