27

我需要使用 memcached 和基于文件的缓存。我在设置中设置了我的缓存:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': 'c:/foo/bar',
    },
    'inmem': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

dummy 是暂时的。文档说:

cache.set('my_key', 'hello, world!', 30)
cache.get('my_key')

好的,但是我现在如何设置和获取仅用于“inmem”缓存后端的缓存(将来的 memcached)?文档没有提到如何做到这一点。

4

5 回答 5

32
CACHES = {
  'default': {
    'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
    'LOCATION': 'c:/foo/bar',
  },
  'inmem': {
    'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
  }
} 

from django.core.cache import get_cache, cache
inmem_cache = get_cache('inmem')
default_cache = get_cache('default')
# default_cache == cache 
于 2011-05-18T18:43:16.553 回答
23

自 Django 1.9 以来,get_cache已弃用。执行以下操作来处理来自“inmem”的键(罗马人回答的补充):

from django.core.cache import caches
caches['inmem'].get(key)
于 2016-11-28T17:49:44.863 回答
3

除了上面 Romans 的回答...您还可以按名称有条件地导入缓存,如果请求不存在,则使用默认值(或任何其他缓存)。

from django.core.cache import cache as default_cache, get_cache
from django.core.cache.backends.base import InvalidCacheBackendError

try:
    cache = get_cache('foo-cache')
except InvalidCacheBackendError:
    cache = default_cache

cache.get('foo')
于 2014-03-19T21:25:05.093 回答
1

从文档:

>>> from django.core.cache import caches
>>> cache1 = caches['myalias']
>>> cache2 = caches['myalias']
>>> cache1 is cache2
True
于 2020-04-01T15:48:07.147 回答
-2

不幸的是,您无法更改用于低级cache.set()cache.get()方法的缓存别名。

这些方法总是根据第 51 行(在 Django 1.3 中)使用“默认”缓存django.core.cache.__init__.py

DEFAULT_CACHE_ALIAS = 'default'

因此,您需要将“默认”缓存设置为要用于低级缓存的缓存,然后将其他别名用于站点缓存、页面缓存和数据库缓存路由等内容。`

于 2011-05-10T21:28:00.840 回答