我有一个Django应用程序设置为使用多个缓存(我希望)。有没有办法将会话设置为使用特定缓存,还是停留在'默认'?
这就是我现在所拥有的:
CACHES = {
'default': {
'BACKEND': 'util.backends.SmartMemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 300,
'ANONYMOUS_ONLY': True
},
'some_other_cache': {
'BACKEND': 'util.backends.SmartMemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 300,
'ANONYMOUS_ONLY': True,
'PREFIX': 'something'
},
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
答案 0 :(得分:3)
cached_db
和cache
后端不支持它,但创建自己的后端很容易:
from django.contrib.sessions.backends.cache import SessionStore as CachedSessionStore
from django.core.cache import get_cache
from django.conf import settings
class SessionStore(CachedSessionStore):
"""
A cache-based session store.
"""
def __init__(self, session_key=None):
self._cache = get_cache(settings.SESSION_CACHE_ALIAS)
super(SessionStore, self).__init__(session_key)
不需要cached_db
后端,因为Redis无论如何都是持久的:)
使用Memcached和cached_db
时,由于SessionStore
的实现方式,它有点复杂。我们完全取代它:
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import get_cache
class SessionStore(DBStore):
"""
Implements cached, database backed sessions. Now with control over the cache!
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
self.cache = get_cache(getattr(settings, 'SESSION_CACHE_ALIAS', 'default'))
def load(self):
data = self.cache.get(self.session_key, None)
if data is None:
data = super(SessionStore, self).load()
self.cache.set(self.session_key, data, settings.SESSION_COOKIE_AGE)
return data
def exists(self, session_key):
return super(SessionStore, self).exists(session_key)
def save(self, must_create=False):
super(SessionStore, self).save(must_create)
self.cache.set(self.session_key, self._session, settings.SESSION_COOKIE_AGE)
def delete(self, session_key=None):
super(SessionStore, self).delete(session_key)
self.cache.delete(session_key or self.session_key)
def flush(self):
"""
Removes the current session data from the database and regenerates the
key.
"""
self.clear()
self.delete(self.session_key)
self.create()