Package: django-cacheops
A slick app that supports automatic or manual queryset caching andautomatic
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 or view as a queryset or by timeextensions for django and jinja2 templatestransparent transaction supportdog-pile prevention mechanisma couple of hacks to make django fasterContentsRequirementsInstallationSetupUsageInvalidationComponentsSimple time-invalidated cacheFile CacheDjango templates integrationJinja2 extensionSpecial topicsTransactionsDog-pile effect preventionMultiple database supportSharing redis instanceCustom serializationUsing memory limitMemory usage cleanupKeeping statsTroubleshootingCAVEATSPerformance tipsWriting a testTODORequirementsPython 3.7+, Django 3.2+ and Redis 4.0+.InstallationUsing pip:$pipinstalldjango-cacheops# Or from github directly$pipinstallgit+https://github.com/Suor/django-cacheops.git@masterSetupAddcacheopsto yourINSTALLED_APPS.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,# connection timeout in seconds, optional'password':'...',# optional'unix_socket_path':''# replaces host and port}# Alternatively the redis connection can be defined using a URL:CACHEOPS_REDIS="redis://localhost:6379/1"# orCACHEOPS_REDIS="unix://path/to/socket?db=1"# or with password (note a colon)CACHEOPS_REDIS="redis://:password@localhost:6379/1"# If you want to use sentinel, specify this variableCACHEOPS_SENTINEL={'locations':[('localhost',26379)],# sentinel locations, required'service_name':'mymaster',# sentinel service name, required'socket_timeout':0.1,# connection timeout in seconds, optional'db':0# redis database, default: 0...# everything else is passed to Sentinel()}# Use your own redis client class, should be compatible or subclass redis.RedisCACHEOPS_CLIENT_CLASS='your.redis.ClientClass'CACHEOPS={# Automatically cache any User.objects.get() calls for 15 minutes# This also includes .first() and .last() calls,# as well as request.user or post.author access,# where Post.author is a foreign key to auth.User'auth.user':{'ops':'get','timeout':60*15},# Automatically cache all gets and queryset fetches# to other django.contrib.auth models for an hour'auth.*':{'ops':{'fetch','get'},'timeout':60*60},# Cache all queries to Permission# 'all' is an alias for {'get', 'fetch', 'count', 'aggregate', 'exists'}'auth.permission':{'ops':'all','timeout':60*60},# Enable manual caching on all other models with default timeout of an hour# Use Post.objects.cache().get(...)#  or Tags.objects.filter(...).order_by(...).cache()# to cache particular ORM request.# Invalidation is still automatic'*.*':{'ops':(),'timeout':60*60},# And since ops is empty by default you can rewrite last line as:'*.*':{'timeout':60*60},# NOTE: binding signals has its overhead, like preventing fast mass deletes,#       you might want to only register whatever you cache and dependencies.# Finally you can explicitely forbid even manual caching with:'some_app.*':None,}You can configure default profile setting withCACHEOPS_DEFAULTS. This way you can rewrite the config above:CACHEOPS_DEFAULTS={'timeout':60*60}CACHEOPS={'auth.user':{'ops':'get','timeout':60*15},'auth.*':{'ops':('fetch','get')},'auth.permission':{'ops':'all'},'*.*':{},}Using'*.*'with non-emptyopsisnot recommendedsince it will easily cache something you don’t intent to or even know about like migrations tables.
The better approach will be restricting by app with'app_name.*'.Besidesopsandtimeoutoptions you can also use:local_get: TrueTo cache simple gets for this model in process local memory.
This is very fast, but is not invalidated in any way until process is restarted.
Still could be useful for extremely rarely changed things.cache_on_save=True | 'field_name'To write an instance to cache upon save.
Cached instance will be retrieved on.get(field_name=...)request.
Setting toTruecauses caching by primary key.Additionally, you can tell cacheops to degrade gracefully on redis fail with:CACHEOPS_DEGRADE_ON_FAILURE=TrueThere is also a possibility to make all cacheops methods and decorators no-op, e.g. for testing:fromdjango.testimportoverride_settings@override_settings(CACHEOPS_ENABLED=False)deftest_something():# ...assertcondUsageAutomatic cachingIt’s automatic you just need to set it up.Manual cachingYou can force any queryset to use cache by calling its.cache()method:Article.objects.filter(tag=2).cache()Here you can specify which ops should be cached for the 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 inPaginatorbut not later articles fetch.
There are five possible actions -get,fetch,count,aggregateandexists.
You can pass any subset of this ops to.cache()method even empty - to turn off caching.
There is, however, a shortcut for the latter: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.You can also override default timeout for particular queryset with.cache(timeout=...).Function cachingYou can cache and invalidate result of a function the same way as a queryset.
Cached results of the next function will be invalidated on anyArticlechange,
addition or deletion:fromcacheopsimportcached_as@cached_as(Article,timeout=120)defarticle_stats():return{'tags':list(Article.objects.values('tag').annotate(Count('id')))'categories':list(Article.objects.values('category').annotate(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 if you want to filter queryset based on arguments,
e.g. to make invalidation more granular, you can use a local function:defarticles_block(category,count=5):qs=Article.objects.filter(category=category)@cached_as(qs,extra=count)def_articles_block():articles=list(qs.filter(photo=True)[:count])iflen(articles)<count:articles+=list(qs.filter(photo=False)[:count-len(articles)])returnarticlesreturn_articles_block()We addedextrahere to make different keys for calls with samecategorybut differentcount. Cache key will also depend on function arguments, so we could just passcountas
an argument to inner function. We also omittedtimeouthere, so a default for the model
will be used.Another possibility is to make function cache invalidate on changes to any one of several models:@cached_as(Article.objects.filter(public=True),Tag)defarticle_stats():return{...}As you can see, we can mix querysets and models here.View cachingYou can also cache and invalidate a view as a queryset. This works mostly the same way as function
caching, but only path of the request parameter is used to construct cache key:fromcacheopsimportcached_view_as@cached_view_as(News)defnews_index(request):# ...returnrender(...)You can passtimeout,extraand several samples the same way as to@cached_as(). Note that you can pass a function asextra:@cached_view_as(News,extra=lambdareq:req.user.is_staff)defnews_index(request):# ... add extra things for staffreturnrender(...)A function passed asextrareceives the same arguments as the cached function.Class based views can also be cached:classNewsIndex(ListView):model=Newsnews_index=cached_view_as(News,...)(NewsIndex.as_view())InvalidationCacheops uses both time and event-driven invalidation. The event-driven one
listens on model signals and invalidates appropriate caches onModel.save(),.delete()and m2m changes.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 of the time this will do what you want, if it won’t you can use
one of the following:fromcacheopsimportinvalidate_obj,invalidate_model,invalidate_allinvalidate_obj(some_article)# invalidates queries affected by some_articleinvalidate_model(Article)# invalidates all queries for modelinvalidate_all()# flush redis cache databaseAnd 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.Turning off and postponing invalidationThere is also a way to turn off invalidation for a while:fromcacheopsimportno_invalidationwithno_invalidation:# ... do some changesobj.save()Also works as decorator:@no_invalidationdefsome_work(...):# ... do some changesobj.save()Combined withtry ... finallyit could be used to postpone invalidation:try:withno_invalidation:# ...finally:invalidate_obj(...)# ... orinvalidate_model(...)Postponing invalidation can speed up batch jobs.Mass updatesNormallyqs.update(…)doesn’t emit any events and thus doesn’t trigger invalidation.
And there is no transparent and efficient way to do that: trying to act on conditions will
invalidate too much if update conditions are orthogonal to many queries conditions,
and to act on specific objects we will need to fetch all of them,
whichQuerySet.update()users generally try to avoid.In the case you actually want to perform the latter cacheops provides a shortcut:qs.invalidated_update(...)Note that all the updated objects are fetched twice, prior and post the update.ComponentsSimple time-invalidated cacheTo cache result of a function call or a view for some time use:fromcacheopsimportcached,cached_view@cached(timeout=number_of_seconds)deftop_articles(category):return...# Some costly queries@cached_view(timeout=number_of_seconds)deftop_articles(request,category=None):# Some costly queriesreturnHttpResponse(...)@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_id)def_articles_json():...returnjson.dumps(...)return_articles_json()You can manually invalidate or update a result of a cached function:top_articles.invalidate(some_category)top_articles.key(some_category).set(new_value)To invalidate cached view you can pass absolute uri instead of request:top_articles.invalidate('http://example.com/page',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@file_cache.cached_view(timeout=number_of_seconds)deftop_articles(request,category):# Some costly queriesreturnHttpResponse(...)# later, on appropriate eventtop_articles.invalidate(some_category)# ortop_articles.key(some_category).set(some_value)# primitivesfile_cache.set(cache_key,data,timeout=None)file_cache.get(cache_key)file_cache.delete(cache_key)It has several improvements upon django built-in file cache, both about high load.
First, it’s 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 cleanfilecache
/path/manage.py cleanfilecache /path/to/non-default/cache/dirDjango templates integrationCacheops provides tags to cache template fragments. 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 useNonefor timeout in@cached_asto use it’s default value for model.To invalidate cached fragment use:fromcacheopsimportinvalidate_fragmentinvalidate_fragment(fragment_name,extra1,...)If you have more complex fragment caching needs, cacheops provides a helper to
make your own template tags which decorate a template fragment in a way
analogous to decorating a function with@cachedor@cached_as.
This isexperimentalfeature for now.To use it createmyapp/templatetags/mycachetags.pyand add something like this there:fromcacheopsimportcached_as,CacheopsLibraryregister=CacheopsLibrary()@register.decorator_tag(takes_context=True)defcache_menu(context,menu_name):fromdjango.utilsimporttranslationfrommyapp.modelsimportFlag,MenuItemrequest=context.get('request')ifrequestandrequest.user.is_staff():# Use noop decorator to bypass caching for staffreturnlambdafunc:funcreturncached_as(# Invalidate cache if any menu item or a flag for menu changesMenuItem,Flag.objects.filter(name='menu'),# Vary for menu name and language, also stamp it as "menu" to be safeextra=("menu",menu_name,translation.get_language()),timeout=24*60*60)@decorator_taghere creates a template tag behaving the same as returned decorator
upon wrapped template fragment. Resulting template tag could be used as follows:{%loadmycachetags%}{%cache_menu"top"%}... the top menu template code ...{%endcache_menu%}... some template code ..{%cache_menu"bottom"%}... the bottom menu template code ...{%endcache_menu%}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.Special topicsTransactionsCacheops transparently supports transactions. This is implemented by following simple rules:Once transaction is dirty (has changes) caching turns off. The reason is that the state of database at this point is only visible to current transaction and should not affect other users and vice versa.Any invalidating calls are scheduled to run on the outer commit of transaction.Savepoints and rollbacks are also handled appropriately.Mind that simple and file cache don’t turn itself off in transactions but work as usual.Dog-pile effect preventionThere is optional locking mechanism to prevent several threads or processes simultaneously performing same heavy task. It works with@cached_as()and querysets:@cached_as(qs,lock=True)defheavy_func(...):# ...foriteminqs.cache(lock=True):# ...It is also possible to specifylock: TrueinCACHEOPSsetting but that would probably be a waste. Locking has no overhead on cache hit though.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':{'ops':'get','db_agnostic':False,'timeout':...}}Sharing redis instanceCacheops provides a way to share a redis instance by adding prefix to cache keys:CACHEOPS_PREFIX=lambdaquery:...# orCACHEOPS_PREFIX='some.module.cacheops_prefix'A most common usage would probably be a prefix by host name:# get_request() returns current request saved to threadlocal by some middlewarecacheops_prefix=lambda_:get_request().get_host()Aqueryobject passed to callback also enables reflection on used databases and tables:defcacheops_prefix(query):query.dbs# A list of databases queriedquery.tables# A list of tables query is invalidated onifset(query.tables)<=HELPER_TABLES:return'helper:'ifquery.tables==['blog_post']:return'blog:'Custom serializationCacheops usespickleby default, employing it’s default protocol. But you can specify your own
it might be any module or a class having.dumps()and.loads()functions. For example you can usedillinstead, which can serialize more things like anonymous functions:CACHEOPS_SERIALIZER='dill'One less obvious use is to fix pickle protocol, to use cacheops cache across python versions:importpickleclassCACHEOPS_SERIALIZER:dumps=lambdadata:pickle.dumps(data,3)loads=pickle.loadsUsing memory limitCacheops offers an “insideout” mode, which idea is instead of conj sets contatining cache keys, cache values contain a checksum of random stamps stored in conj keys, which are checked on each read to stay the same. To use that add to settings:CACHEOPS_INSIDEOUT=True# Might become default in futureAnd set upmaxmemoryandmaxmemory-policyin redis config:maxmemory 4gb
maxmemory-policy volatile-lru  # or other volatile-*Note that using any ofallkeys-*policies might drop important invalidation structures of cacheops and lead to stale cache.Memory usage cleanupThis does not apply to “insideout” mode. This issue doesn’t happen there.In some cases, cacheops may leave some conjunction keys of expired cache keys in redis without being able to invalidate them. Those will still expire with age, but in the meantime may cause issues like slow invalidation (even “BUSY Redis …”) and extra memory usage. To prevent that it is advised to not cache complex queries, seePerfomance tips, 5.Cacheops ships with acacheops.reap_conjsfunction that can clean up these keys,
ignoring conjunction sets with some reasonable size. It can be called using thereapconjsmanagement command:./manage.py reapconjs --chunk-size=100 --min-conj-set-size=10000  # with custom values
./manage.py reapconjs                                             # with default values (chunks=1000, min size=1000)The command is a small wrapper that calls a function with the main logic. You can also call it from your code, for example from a Celery task:fromcacheopsimportreap_conjs@app.taskdefreap_conjs_task():reap_conjs(chunk_size=2000,min_conj_set_size=100,)Keeping statsCacheops providescache_readandcache_invalidatedsignals for you to keep track.Cache read signal is emitted immediately after each cache lookup. Passed arguments are:sender- model class if queryset cache is fetched,func- decorated function andhit- fetch success as boolean value.Here is a simple stats implementation:fromcacheops.signalsimportcache_readfromstatsd.defaults.djangoimportstatsddefstats_collector(sender,func,hit,**kwargs):event='hit'ifhitelse'miss'statsd.incr('cacheops.%s'%event)cache_read.connect(stats_collector)Cache invalidation signal is emitted after object, model or global invalidation passingsenderandobj_dictargs. Note that during normal operation cacheops only uses object invalidation, calling it once for each model create/delete and twice for update: passing old and new object dictionary.TroubleshootingCAVEATSConditions other than__exact,__inand__isnull=Truedon’t make invalidation
more granular.Conditions on TextFields, FileFields and BinaryFields don’t make it either.
One should not test on their equality anyway. SeeCACHEOPS_SKIP_FIELDSthough.Update of “selected_related” object does not invalidate cache for queryset.
Use.prefetch_related()instead.Mass updates don’t trigger invalidation by default. But see.invalidated_update().Sliced queries are invalidated as non-sliced ones.Doesn’t work with.raw()and other sql queries.Conditions on subqueries don’t affect invalidation.Doesn’t work right with multi-table inheritance.Here 1, 2, 3, 5 are part of the design compromise, trying to solve them will make
things complicated and slow. 7 can be implemented if needed, but it’s
probably counter-productive since one can just break queries into simpler 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,
see, however,.invalidated_update(). 8 is postponed until it will gain
more interest or a champion willing to implement it emerges.All unsupported things could still be used easily enough with the help of@cached_as().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 the 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. Note that this is a micro-optimization technique. Using it is only desirable in the hottest places, not everywhere.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 a 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 (negligable for “insideout” mode). You can disable caching if more than some amount of fields is used in filter simultaneously.Split database queries into smaller ones when you cache them. This goes against usual approach, but this allows invalidation to be more granular: smaller parts will be invalidated independently and each part will invalidate more precisely.Post.objects.filter(category__slug="foo")# A single database query, but will be invalidated not only on# any Category with .slug == "foo" change, but also for any Post changePost.objects.filter(category=Category.objects.get(slug="foo"))# Two queries, each invalidates only on a granular event:# either category.slug == "foo" or Post with .category_id == <whatever is there>Writing a testWriting a test for an issue you are experiencing can speed up its resolution a lot.
Here is how you do that. I suppose you have some application code causing it.Make a fork.Install all fromrequirements-test.txt.Ensure you can run tests withpytest.Copy relevant models code totests/models.py.Go totests/tests.pyand paste code causing exception toIssueTests.test_{issue_number}.Executepytest-k{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.TODOfaster .get() handling for simple cases such as get by pk/id, with simple key calculationintegrate previous one with prefetch_related()shard cache between multiple redisesrespect subqueries?respect headers in @cached_view*?group invalidate_obj() calls?a postpone invalidation context manager/decorator?fast mode: store cache in local memory, but check in with redis if it’s validan interface for complex fields to extract exact on parts or transforms: ArrayField.len => field__len=?, ArrayField[0] => field__0=?, JSONField[‘some_key’] => field__some_key=?custom cache eviction strategy in luacache a string directly (no pickle) for direct serving (custom key function?)