Django multiple caching BACKEND routers howto?

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

I currently have this in my configuration file, but I don’t know how to write a router to complete caching.

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

I use the structure of multiple databases, and I know how to write multiple database routers.

in settings.py

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

Does anyone know how to make Django BACKEND caching a router?

thanks

+4
source share
2 answers

I do not believe that the Django cache framework can mimic db routing at all .

For a site cache using the middleware cache structure, you must specify the cache name in the settings. py for example:

 CACHE_MIDDLEWARE_ALIAS = "my_cache_alias" 

For page cache, you can manually specify the cache name in the decorator, for example:

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

I'm not sure that cache routing really makes sense for caching sites and pages, so I have no problem with how this is provided.

Now, for your case, when you use MySQL as the back-up of the database cache, you can configure it and create a router according to the jango docs section in the database caching . For example, this will be your CACHES parameter:

 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 just like a DB router (as you should see from the doc section in database caching and multiple databases ), except that it returns a cache alias instead of a db alias.

+3
source

eg

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 details in the Djangos cache structure (section: Accessing the cache )

0
source

Source: https://habr.com/ru/post/1342597/


All Articles