开发者

Django multiple caching BACKEND routers howto?

So I want to cache some data in mysql and some in memcached.

at the moment I have this In my config file, but i don't know how to write router for cache back end.

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:1121开发者_运维百科1',
    }
}

I use multi databases structure and I know how to write multi database routers.

in settings.py

DATABASE_ROUTERS = ['oceankeys.dbrouter.SphinxRouter','oceankeys.dbrouter.DefaultDbRouter']

Any one know how to make Django caching BACKEND router?

Thanks


I don't believe the Django cache framework can mimic db routing in general.

For the site cache using the cache framework middleware you have to specify the name of the cache in settings.py, e.g.:

CACHE_MIDDLEWARE_ALIAS = "my_cache_alias"

For a page cache you can manually specify the name of the cache in the decorator, e.g.:

@cache_page(60 * 15, cache="my_cache_alias")
    def my_view(request):
    ...

I'm not sure cache routing really makes sense for site and page caching so I don't have a problem with the way this is designed.

Now, for your case where you are using MySQL as a database cache backend you can set it up and make a router as per the Django docs section on database caching. For example, this would be your CACHES setting:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
    'my_cache_alias': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

Then create a router that identifies which cache backend to use for which models. It looks and works exactly like DB router (as you should be able to see from the doc section on database caching and multiple databases) with the exception that it returns a cache alias instead of db alias.


e.g

settings.py

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    },
    'myalias':{
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

views.py

from django.core.cache import caches
cache = caches['myalias']
cache.set('my_key', 'hello, world!', 30)
print cache.get('my_key')

You can see the detail in Django’s cache framework (section:Accessing the cache)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜