如何在Django中使用2个不同的缓存后端?

rob*_*s85 19 django django-cache django-caching

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

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': 'c:/foo/bar',
    },
    'inmem': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}
Run Code Online (Sandbox Code Playgroud)

假的是暂时的.文件说:

cache.set('my_key', 'hello, world!', 30)
cache.get('my_key')
Run Code Online (Sandbox Code Playgroud)

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

小智 27

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 
Run Code Online (Sandbox Code Playgroud)


rin*_*ahn 12

自Django 1.9以来,get_cache已被弃用.执行以下操作来解决"inmem"中的键(除了Romans的回答):

from django.core.cache import caches
caches['inmem'].get(key)
Run Code Online (Sandbox Code Playgroud)