Skip to content

Instantly share code, notes, and snippets.

@stefanfoulis
Created September 13, 2016 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanfoulis/0c8db7211008d9e66fa400c7c3b0463b to your computer and use it in GitHub Desktop.
Save stefanfoulis/0c8db7211008d9e66fa400c7c3b0463b to your computer and use it in GitHub Desktop.
Snippets for an eventual better django-dbcache app

django-dbcache

A django cache backend that treats the db cache as a first class citizen.

The cache backend in django.core.cache.backends.db only works on the default database connection. Using the same connection as for regular model access can cause weird transaction related deadlocks and similar problems.

django-dbcache allows using a separate database connection just for cache.

Eventually this backend should implement database specific optimisations, like using postgres' key value store.

Why? Redis is probably faster than postgres, but it also has everything in RAM. For caches that don't get used that often, or have values that can stay in the cache unchanged for a very long time, postgres actually has better characteristics than redis. It does all sorts of optimisations on read or frequent access. For large installations with many, many not so active websites the resource usage characteristics of postgres are better than redis, which has a high idle consumption.

# stuff based on django.core.cache.backends.db
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
app_to_database = {
'django_cache': 'cache',
}
class CacheRouter(object):
def db_for_read(self, model, **hints):
return app_to_database.get(model._meta.app_label, None)
def db_for_write(self, model, **hints):
return app_to_database.get(model._meta.app_label, None)
def allow_syncdb(self, db, model):
_db = app_to_database.get(model._meta.app_label, None)
return db == _db if _db else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment