Django Multiple Caches - How to choose which cache

2019-07-28 01:23发布

I have a Django app set up to use multiple caches (I hope). Is there a way to set the session to use a specific cache, or is it stuck on 'default'?

Here's what i have now:

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'

1条回答
狗以群分
2楼-- · 2019-07-28 01:42

The cached_db and cache backends don't support it, but it's easy to create your own:

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)

No need for a cached_db backend since Redis is persistent anyway :)


When using Memcached and cached_db, its a bit more complex because of how that SessionStore is implemented. We just replace it completely:

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()
查看更多
登录 后发表回答