Package: django-cacheops-with-stats
A slick app that supports automatic or manual queryset caching and automatic
granular event-driven invalidation.It usesredisas backend for ORM cache and redis or
filesystem for simple time-invalidated one.And there is more to it:decorators to cache any user function as queryset or by timeextensions for django and jinja2 templates to cache template fragments as querysets or by timeconcurrent file cache with a decoratora couple of hacks to make django fasterRequirementsPython 2.6, 2.7 or 3.3, Django 1.2+ and Redis 2.6+.InstallationUsing pip:$ pip install django-cacheopsOr you can get latest one from github:$ git clone git://github.com/Suor/django-cacheops.git
$ ln -s `pwd`/django-cacheops/cacheops/ /somewhere/on/python/path/SetupAddcacheopsto yourINSTALLED_APPSbefore any apps that use it.Setup redis connection and enable caching for desired models:CACHEOPS_REDIS={'host':'localhost',# redis-server is on same machine'port':6379,# default redis port'db':1,# SELECT non-default redis database# using separate redis db or redis instance# is highly recommended'socket_timeout':3,}CACHEOPS={# Automatically cache any User.objects.get() calls for 15 minutes# This includes request.user or post.author access,# where Post.author is a foreign key to auth.User'auth.user':('get',60*15),# Automatically cache all gets, queryset fetches and counts# to other django.contrib.auth models for an hour'auth.*':('all',60*60),# Enable manual caching on all news models with default timeout of an hour# Use News.objects.cache().get(...)#  or Tags.objects.filter(...).order_by(...).cache()# to cache particular ORM request.# Invalidation is still automatic'news.*':('just_enable',60*60),# Automatically cache count requests for all other models for 15 min'*.*':('count',60*15),}Additionally, you can tell cacheops to degrade gracefully on redis fail with:CACHEOPS_DEGRADE_ON_FAILURE=TrueUsageAutomatic caching.It’s automatic you just need to set it up.Manual caching.You can force any queryset to use cache by calling it’s.cache()method:Article.objects.filter(tag=2).cache()Here you can specify which ops should be cached for queryset, for example, this code:qs=Article.objects.filter(tag=2).cache(ops=['count'])paginator=Paginator(objects,ipp)articles=list(pager.page(page_num))# hits databasewill cache.count()call in Paginator but not later in articles fetch.
There are three possible actions -get,fetchandcount. You can
pass any subset of this ops to.cache()method even empty to turn off caching.
There are, however, a shortcut for it:qs=Article.objects.filter(visible=True).nocache()qs1=qs.filter(tag=2)# hits databaseqs2=qs.filter(category=3)# hits it once moreIt is useful when you want to disable automatic caching on particular queryset.Function caching.You can cache and invalidate result of a function the same way as a queryset.
Cache of next function will be invalidated on anyArticlechange, addition
or deletion:fromcacheopsimportcached_as@cached_as(Article)defarticle_stats():return{'tags':list(Article.objects.values('tag').annotate(count=Count('id')))'categories':list(Article.objects.values('category').annotate(count=Count('id')))}Note that we are using list on both querysets here, it’s because we don’t want
to cache queryset objects but their results.Also note that cache key does not depend on arguments of a function, so it’s result
should not, either. This is done to enable caching of view functions. Instead
you should use a local function:defarticles_block(category,count=5):@cached_as(Article.objects.filter(category=category),extra=count)def_articles_block():qs=Article.objects.filter(category=category)articles=list(qs.filter(photo=True)[:count])iflen(articles)<count:articles+=list(qs[:count-len(articles)])returnarticlesreturn_articles_block()Using local function gives additional advantage: we can filter queryset used
in@cached_as()to make invalidation more granular. We also add anextrato make different keys for calls with samecategorybut differentcount.InvalidationCacheops uses both time and event-driven invalidation. The event-driven one
listens on model signals and invalidates appropriate caches onModel.save()and.delete().Invalidation tries to be granular which means it won’t invalidate a queryset
that cannot be influenced by added/updated/deleted object judging by query
conditions. Most time this will do what you want, if it’s not you can use one
of the following:fromcacheopsimportinvalidate_obj,invalidate_modelinvalidate_obj(some_article)# invalidates queries affected by some_articleinvalidate_model(Article)# invalidates all queries for modelAnd last there isinvalidatecommand:./manage.py invalidate articles.Article.34  # same as invalidate_obj
./manage.py invalidate articles.Article     # same as invalidate_model
./manage.py invalidate articles   # invalidate all models in articlesAnd the one that FLUSHES cacheops redis database:./manage.py invalidate allDon’t use that if you share redis database for both cache and something else.Multiple database supportBy default cacheops considers query result is same for same query, not depending on database queried. That could be changed withdb_agnosticcache profile option:CACHEOPS={'some.model':('get',TIMEOUT,{'db_agnostic':False}),# ...}Simple time-invalidated cacheTo cache result of a function call for some time use:fromcacheopsimportcached@cached(timeout=number_of_seconds)deftop_articles(category):return...# Some costly queries@cached()will generate separate entry for each combination of decorated function and its
arguments. Also you can useextrasame way as in@cached_as(), most useful for nested functions:@propertydefarticles_json(self):@cached(timeout=10*60,extra=self.category)def_articles_json():...returnjson.dumps(...)return_articles_json()You can manually invalidate cached function result this way:top_articles.invalidate(some_category)Cacheops also provides get/set primitives for simple cache:fromcacheopsimportcachecache.set(cache_key,data,timeout=None)cache.get(cache_key)cache.delete(cache_key)cache.getwill raiseCacheMissif nothing is stored for given key:fromcacheopsimportcache,CacheMisstry:result=cache.get(key)exceptCacheMiss:...# deal with itFile CacheFile based cache can be used the same way as simple time-invalidated one:fromcacheopsimportfile_cache@file_cache.cached(timeout=number_of_seconds)deftop_articles(category):return...# Some costly queries# later, on appropriate eventtop_articles.invalidate(some_category)# primitivesfile_cache.set(cache_key,data,timeout=None)file_cache.get(cache_key)file_cache.delete(cache_key)It have several improvements upon django built-in file cache, both about high load. First, it is safe against concurrent writes. Second, it’s invalidation is done as separate task, you’ll need to call this from crontab for that to work:/path/manage.py cleanfilecacheDjango templates integrationCacheops provides tags to cache template fragments for Django 1.4+. They mimic@cached_asand@cacheddecorators, however they require explicit naming of each fragment:{%loadcacheops%}{%cached_as<queryset><timeout><fragment_name>[<extra1><extra2>...]%}... some template code ...{%endcached_as%}{%cached<timeout><fragment_name>[<extra1><extra2>...]%}... some template code ...{%endcached%}You can use0for timeout in@cached_asto use it’s default value for model.Jinja2 extensionAddcacheops.jinja2.cacheto your extensions and use:{%cached_as<queryset>[,timeout=<timeout>][,extra=<keyaddition>]%}... some template code ...{%endcached_as%}or{%cached[timeout=<timeout>][,extra=<keyaddition>]%}...{%endcached%}Tags work the same way as corresponding decorators.CAVEATSConditions other than__exactor__indon’t provide more granularity for
invalidation.Conditions on related models don’t provide it either.Update of “selected_related” object does not invalidate cache for queryset.Mass updates don’t trigger invalidation.ORDER BY and LIMIT/OFFSET don’t affect invalidation.Doesn’t work with RawQuerySet.Conditions on subqueries don’t affect invalidation.Doesn’t work right with multi-table inheritance.Aggregates is not implemented yet.Timeout in queryset and@cached_as()cannot be larger than default.Here 1, 3, 5, 10 are part of design compromise, trying to solve them will make
things complicated and slow. 2 and 7 can be implemented if needed, but it’s
probably counter-productive since one can just break queries into simple ones,
which cache better. 4 is a deliberate choice, making it “right” will flush
cache too much when update conditions are orthogonal to most queries conditions.
6 can be cached asSomeModel.objects.all()but@cached_as()someway covers that
and is more flexible. 8 is postponed until it will gain more interest or a champion willing to
implement it emerge.Performance tipsHere come some performance tips to make cacheops and Django ORM faster.When you use cache you pickle and unpickle lots of django model instances, which could be slow. You can optimize django models serialization withdjango-pickling.Constructing querysets is rather slow in django, mainly because most ofQuerySetmethods clone self, then change it and return a clone. Original queryset is usually thrown away. Cacheops adds.inplace()method, which makes queryset mutating, preventing useless cloning:items = Item.objects.inplace().filter(category=12).order_by('-date')[:20]You can revert queryset to cloning state using.cloning()call.More to 2, there is abug in django 1.4-,
which sometimes make queryset cloning very slow. You can use any patch from this ticket to fix it.Use template fragment caching when possible, it’s way more fast because you don’t need to generate anything. Also pickling/unpickling a string is much faster than list of model instances.Run separate redis instance for cache with disabledpersistence. You can manually callSAVEorBGSAVEto stay hot upon server restart.If you filter queryset on many different or complex conditions cache could degrade performance (comparing to uncached db calls) in consequence of frequent cache misses. Disable cache in such cases entirely or on some heuristics which detect if this request would be probably hit. E.g. enable cache if only some primary fields are used in filter.Caching querysets with large amount of filters also slows down all subsequent invalidation on that model. You can disable caching if more than some amount of fields is used in filter simultaneously.Writing a testWriting a test for an issue you are having can speed up it’s resolution a lot. Here is how you do that. I am supposing you have some application code causing it.Make a fork.Install all fromtest_requirements.txt.Ensure you can run tests with./run_tests.py.Copy relevant models code tohttps://github.com/Suor/django-cacheops/blob/master/tests/models.pyGo tohttps://github.com/Suor/django-cacheops/blob/master/tests/tests.pyand paste code causing exception toIssueTests.test_{issue_number}.Execute./run_tests.py IssueTests.test_{issue_number}and see it failing.Cut down model and test code until error disappears and make a step back.Commit changes and make a pull request.TODOautodiscover ways to stringify things, make a better error message/docsbetter invalidate_model()add local cache (cleared at the and of request?)support transactionsa way to turn off or postpone invalidationfaster .get() handling for simple cases such as get by pk/id, with simple key calculationintegrate with prefetch_related()fast mode: store cache in local memory, but check in with redis if it’s validshard cache between multiple redisesdisable cache if select_for_update() called (or if _for_write set?)lazy methods on querysets (calculate cache key from methods called)