• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

cacheops/H03-May-2021-1,9791,399

django_cacheops.egg-info/H03-May-2022-850558

tests/H03-May-2021-2,1701,578

CHANGELOGH A D03-May-202112.2 KiB371316

LICENSEH A D05-Jan-20201.5 KiB2822

MANIFEST.inH A D20-Oct-2020222 109

PKG-INFOH A D03-May-202134.3 KiB849557

README.rstH A D30-Apr-202126.8 KiB817527

bench.pyH A D05-Jan-20202.5 KiB9673

manage.pyH A D05-Jan-2020249 116

run_tests.pyH A D05-Jan-20201.1 KiB4326

setup.cfgH A D03-May-2021102 117

setup.pyH A D03-May-20211.8 KiB6151

tox.iniH A D01-May-20211.4 KiB6355

README.rst

1Cacheops |Build Status| |Gitter|
2========
3
4A slick app that supports automatic or manual queryset caching and automatic
5granular event-driven invalidation.
6
7It uses `redis <http://redis.io/>`_ as backend for ORM cache and redis or
8filesystem for simple time-invalidated one.
9
10And there is more to it:
11
12- decorators to cache any user function or view as a queryset or by time
13- extensions for django and jinja2 templates
14- transparent transaction support
15- dog-pile prevention mechanism
16- a couple of hacks to make django faster
17
18
19Requirements
20------------
21
22Python 3.5+, Django 2.1+ and Redis 4.0+.
23
24
25Installation
26------------
27
28Using pip:
29
30.. code:: bash
31
32    $ pip install django-cacheops
33
34    # Or from github directly
35    $ pip install git+https://github.com/Suor/django-cacheops.git@master
36
37
38Setup
39-----
40
41Add ``cacheops`` to your ``INSTALLED_APPS``.
42
43Setup redis connection and enable caching for desired models:
44
45.. code:: python
46
47    CACHEOPS_REDIS = {
48        'host': 'localhost', # redis-server is on same machine
49        'port': 6379,        # default redis port
50        'db': 1,             # SELECT non-default redis database
51                             # using separate redis db or redis instance
52                             # is highly recommended
53
54        'socket_timeout': 3,   # connection timeout in seconds, optional
55        'password': '...',     # optional
56        'unix_socket_path': '' # replaces host and port
57    }
58
59    # Alternatively the redis connection can be defined using a URL:
60    CACHEOPS_REDIS = "redis://localhost:6379/1"
61    # or
62    CACHEOPS_REDIS = "unix://path/to/socket?db=1"
63    # or with password (note a colon)
64    CACHEOPS_REDIS = "redis://:password@localhost:6379/1"
65
66    # If you want to use sentinel, specify this variable
67    CACHEOPS_SENTINEL = {
68        'locations': [('localhost', 26379)], # sentinel locations, required
69        'service_name': 'mymaster',          # sentinel service name, required
70        'socket_timeout': 0.1,               # connection timeout in seconds, optional
71        'db': 0                              # redis database, default: 0
72        ...                                  # everything else is passed to Sentinel()
73    }
74
75    # To use your own redis client class,
76    # should be compatible or subclass cacheops.redis.CacheopsRedis
77    CACHEOPS_CLIENT_CLASS = 'your.redis.ClientClass'
78
79    CACHEOPS = {
80        # Automatically cache any User.objects.get() calls for 15 minutes
81        # This also includes .first() and .last() calls,
82        # as well as request.user or post.author access,
83        # where Post.author is a foreign key to auth.User
84        'auth.user': {'ops': 'get', 'timeout': 60*15},
85
86        # Automatically cache all gets and queryset fetches
87        # to other django.contrib.auth models for an hour
88        'auth.*': {'ops': {'fetch', 'get'}, 'timeout': 60*60},
89
90        # Cache all queries to Permission
91        # 'all' is an alias for {'get', 'fetch', 'count', 'aggregate', 'exists'}
92        'auth.permission': {'ops': 'all', 'timeout': 60*60},
93
94        # Enable manual caching on all other models with default timeout of an hour
95        # Use Post.objects.cache().get(...)
96        #  or Tags.objects.filter(...).order_by(...).cache()
97        # to cache particular ORM request.
98        # Invalidation is still automatic
99        '*.*': {'ops': (), 'timeout': 60*60},
100
101        # And since ops is empty by default you can rewrite last line as:
102        '*.*': {'timeout': 60*60},
103
104        # NOTE: binding signals has its overhead, like preventing fast mass deletes,
105        #       you might want to only register whatever you cache and dependencies.
106
107        # Finally you can explicitely forbid even manual caching with:
108        'some_app.*': None,
109    }
110
111You can configure default profile setting with ``CACHEOPS_DEFAULTS``. This way you can rewrite the config above:
112
113.. code:: python
114
115    CACHEOPS_DEFAULTS = {
116        'timeout': 60*60
117    }
118    CACHEOPS = {
119        'auth.user': {'ops': 'get', 'timeout': 60*15},
120        'auth.*': {'ops': ('fetch', 'get')},
121        'auth.permission': {'ops': 'all'},
122        '*.*': {},
123    }
124
125Using ``'*.*'`` with non-empty ``ops`` is **not recommended**
126since it will easily cache something you don't intent to or even know about like migrations tables.
127The better approach will be restricting by app with ``'app_name.*'``.
128
129Besides ``ops`` and ``timeout`` options you can also use:
130
131``local_get: True``
132    To cache simple gets for this model in process local memory.
133    This is very fast, but is not invalidated in any way until process is restarted.
134    Still could be useful for extremely rarely changed things.
135
136``cache_on_save=True | 'field_name'``
137    To write an instance to cache upon save.
138    Cached instance will be retrieved on ``.get(field_name=...)`` request.
139    Setting to ``True`` causes caching by primary key.
140
141Additionally, you can tell cacheops to degrade gracefully on redis fail with:
142
143.. code:: python
144
145    CACHEOPS_DEGRADE_ON_FAILURE = True
146
147There is also a possibility to make all cacheops methods and decorators no-op, e.g. for testing:
148
149.. code:: python
150
151    from django.test import override_settings
152
153    @override_settings(CACHEOPS_ENABLED=False)
154    def test_something():
155        # ...
156        assert cond
157
158
159Usage
160-----
161
162| **Automatic caching**
163
164It's automatic you just need to set it up.
165
166
167| **Manual caching**
168
169You can force any queryset to use cache by calling its ``.cache()`` method:
170
171.. code:: python
172
173    Article.objects.filter(tag=2).cache()
174
175
176Here you can specify which ops should be cached for the queryset, for example, this code:
177
178.. code:: python
179
180    qs = Article.objects.filter(tag=2).cache(ops=['count'])
181    paginator = Paginator(objects, ipp)
182    articles = list(pager.page(page_num)) # hits database
183
184
185will cache count call in ``Paginator`` but not later articles fetch.
186There are five possible actions - ``get``, ``fetch``, ``count``, ``aggregate`` and ``exists``.
187You can pass any subset of this ops to ``.cache()`` method even empty - to turn off caching.
188There is, however, a shortcut for the latter:
189
190.. code:: python
191
192    qs = Article.objects.filter(visible=True).nocache()
193    qs1 = qs.filter(tag=2)       # hits database
194    qs2 = qs.filter(category=3)  # hits it once more
195
196
197It is useful when you want to disable automatic caching on particular queryset.
198
199You can also override default timeout for particular queryset with ``.cache(timeout=...)``.
200
201
202| **Function caching**
203
204You can cache and invalidate result of a function the same way as a queryset.
205Cached results of the next function will be invalidated on any ``Article`` change,
206addition or deletion:
207
208.. code:: python
209
210    from cacheops import cached_as
211
212    @cached_as(Article, timeout=120)
213    def article_stats():
214        return {
215            'tags': list(Article.objects.values('tag').annotate(Count('id')))
216            'categories': list(Article.objects.values('category').annotate(Count('id')))
217        }
218
219
220Note that we are using list on both querysets here, it's because we don't want
221to cache queryset objects but their results.
222
223Also note that if you want to filter queryset based on arguments,
224e.g. to make invalidation more granular, you can use a local function:
225
226.. code:: python
227
228    def articles_block(category, count=5):
229        qs = Article.objects.filter(category=category)
230
231        @cached_as(qs, extra=count)
232        def _articles_block():
233            articles = list(qs.filter(photo=True)[:count])
234            if len(articles) < count:
235                articles += list(qs.filter(photo=False)[:count-len(articles)])
236            return articles
237
238        return _articles_block()
239
240We added ``extra`` here to make different keys for calls with same ``category`` but different
241``count``. Cache key will also depend on function arguments, so we could just pass ``count`` as
242an argument to inner function. We also omitted ``timeout`` here, so a default for the model
243will be used.
244
245Another possibility is to make function cache invalidate on changes to any one of several models:
246
247.. code:: python
248
249    @cached_as(Article.objects.filter(public=True), Tag)
250    def article_stats():
251        return {...}
252
253As you can see, we can mix querysets and models here.
254
255
256| **View caching**
257
258You can also cache and invalidate a view as a queryset. This works mostly the same way as function
259caching, but only path of the request parameter is used to construct cache key:
260
261.. code:: python
262
263    from cacheops import cached_view_as
264
265    @cached_view_as(News)
266    def news_index(request):
267        # ...
268        return render(...)
269
270You can pass ``timeout``, ``extra`` and several samples the same way as to ``@cached_as()``. Note that you can pass a function as ``extra``:
271
272.. code:: python
273
274    @cached_view_as(News, extra=lambda req: req.user.is_staff)
275    def news_index(request):
276        # ... add extra things for staff
277        return render(...)
278
279A function passed as ``extra`` receives the same arguments as the cached function.
280
281Class based views can also be cached:
282
283.. code:: python
284
285    class NewsIndex(ListView):
286        model = News
287
288    news_index = cached_view_as(News, ...)(NewsIndex.as_view())
289
290
291Invalidation
292------------
293
294Cacheops uses both time and event-driven invalidation. The event-driven one
295listens on model signals and invalidates appropriate caches on ``Model.save()``, ``.delete()``
296and m2m changes.
297
298Invalidation tries to be granular which means it won't invalidate a queryset
299that cannot be influenced by added/updated/deleted object judging by query
300conditions. Most of the time this will do what you want, if it won't you can use
301one of the following:
302
303.. code:: python
304
305    from cacheops import invalidate_obj, invalidate_model, invalidate_all
306
307    invalidate_obj(some_article)  # invalidates queries affected by some_article
308    invalidate_model(Article)     # invalidates all queries for model
309    invalidate_all()              # flush redis cache database
310
311And last there is ``invalidate`` command::
312
313    ./manage.py invalidate articles.Article.34  # same as invalidate_obj
314    ./manage.py invalidate articles.Article     # same as invalidate_model
315    ./manage.py invalidate articles   # invalidate all models in articles
316
317And the one that FLUSHES cacheops redis database::
318
319    ./manage.py invalidate all
320
321Don't use that if you share redis database for both cache and something else.
322
323
324| **Turning off and postponing invalidation**
325
326There is also a way to turn off invalidation for a while:
327
328.. code:: python
329
330    from cacheops import no_invalidation
331
332    with no_invalidation:
333        # ... do some changes
334        obj.save()
335
336Also works as decorator:
337
338.. code:: python
339
340    @no_invalidation
341    def some_work(...):
342        # ... do some changes
343        obj.save()
344
345Combined with ``try ... finally`` it could be used to postpone invalidation:
346
347.. code:: python
348
349    try:
350        with no_invalidation:
351            # ...
352    finally:
353        invalidate_obj(...)
354        # ... or
355        invalidate_model(...)
356
357Postponing invalidation can speed up batch jobs.
358
359
360| **Mass updates**
361
362Normally `qs.update(...)` doesn't emit any events and thus doesn't trigger invalidation.
363And there is no transparent and efficient way to do that: trying to act on conditions will
364invalidate too much if update conditions are orthogonal to many queries conditions,
365and to act on specific objects we will need to fetch all of them,
366which `QuerySet.update()` users generally try to avoid.
367
368In the case you actually want to perform the latter cacheops provides a shortcut:
369
370.. code:: python
371
372    qs.invalidated_update(...)
373
374Note that all the updated objects are fetched twice, prior and post the update.
375
376
377Simple time-invalidated cache
378-----------------------------
379
380To cache result of a function call or a view for some time use:
381
382.. code:: python
383
384    from cacheops import cached, cached_view
385
386    @cached(timeout=number_of_seconds)
387    def top_articles(category):
388        return ... # Some costly queries
389
390    @cached_view(timeout=number_of_seconds)
391    def top_articles(request, category=None):
392        # Some costly queries
393        return HttpResponse(...)
394
395
396``@cached()`` will generate separate entry for each combination of decorated function and its
397arguments. Also you can use ``extra`` same way as in ``@cached_as()``, most useful for nested
398functions:
399
400.. code:: python
401
402    @property
403    def articles_json(self):
404        @cached(timeout=10*60, extra=self.category_id)
405        def _articles_json():
406            ...
407            return json.dumps(...)
408
409        return _articles_json()
410
411
412You can manually invalidate or update a result of a cached function:
413
414.. code:: python
415
416    top_articles.invalidate(some_category)
417    top_articles.key(some_category).set(new_value)
418
419
420To invalidate cached view you can pass absolute uri instead of request:
421
422.. code:: python
423
424    top_articles.invalidate('http://example.com/page', some_category)
425
426
427Cacheops also provides get/set primitives for simple cache:
428
429.. code:: python
430
431    from cacheops import cache
432
433    cache.set(cache_key, data, timeout=None)
434    cache.get(cache_key)
435    cache.delete(cache_key)
436
437
438``cache.get`` will raise ``CacheMiss`` if nothing is stored for given key:
439
440.. code:: python
441
442    from cacheops import cache, CacheMiss
443
444    try:
445        result = cache.get(key)
446    except CacheMiss:
447        ... # deal with it
448
449
450File Cache
451----------
452
453File based cache can be used the same way as simple time-invalidated one:
454
455.. code:: python
456
457    from cacheops import file_cache
458
459    @file_cache.cached(timeout=number_of_seconds)
460    def top_articles(category):
461        return ... # Some costly queries
462
463    @file_cache.cached_view(timeout=number_of_seconds)
464    def top_articles(request, category):
465        # Some costly queries
466        return HttpResponse(...)
467
468    # later, on appropriate event
469    top_articles.invalidate(some_category)
470    # or
471    top_articles.key(some_category).set(some_value)
472
473    # primitives
474    file_cache.set(cache_key, data, timeout=None)
475    file_cache.get(cache_key)
476    file_cache.delete(cache_key)
477
478
479It has several improvements upon django built-in file cache, both about high load.
480First, it's safe against concurrent writes. Second, it's invalidation is done as separate task,
481you'll need to call this from crontab for that to work::
482
483    /path/manage.py cleanfilecache
484    /path/manage.py cleanfilecache /path/to/non-default/cache/dir
485
486
487Django templates integration
488----------------------------
489
490Cacheops provides tags to cache template fragments. They mimic ``@cached_as``
491and ``@cached`` decorators, however, they require explicit naming of each fragment:
492
493.. code:: django
494
495    {% load cacheops %}
496
497    {% cached_as <queryset> <timeout> <fragment_name> [<extra1> <extra2> ...] %}
498        ... some template code ...
499    {% endcached_as %}
500
501    {% cached <timeout> <fragment_name> [<extra1> <extra2> ...] %}
502        ... some template code ...
503    {% endcached %}
504
505You can use ``None`` for timeout in ``@cached_as`` to use it's default value for model.
506
507To invalidate cached fragment use:
508
509.. code:: python
510
511    from cacheops import invalidate_fragment
512
513    invalidate_fragment(fragment_name, extra1, ...)
514
515If you have more complex fragment caching needs, cacheops provides a helper to
516make your own template tags which decorate a template fragment in a way
517analogous to decorating a function with ``@cached`` or ``@cached_as``.
518This is **experimental** feature for now.
519
520To use it create ``myapp/templatetags/mycachetags.py`` and add something like this there:
521
522.. code:: python
523
524    from cacheops import cached_as, CacheopsLibrary
525
526    register = CacheopsLibrary()
527
528    @register.decorator_tag(takes_context=True)
529    def cache_menu(context, menu_name):
530        from django.utils import translation
531        from myapp.models import Flag, MenuItem
532
533        request = context.get('request')
534        if request and request.user.is_staff():
535            # Use noop decorator to bypass caching for staff
536            return lambda func: func
537
538        return cached_as(
539            # Invalidate cache if any menu item or a flag for menu changes
540            MenuItem,
541            Flag.objects.filter(name='menu'),
542            # Vary for menu name and language, also stamp it as "menu" to be safe
543            extra=("menu", menu_name, translation.get_language()),
544            timeout=24 * 60 * 60
545        )
546
547``@decorator_tag`` here creates a template tag behaving the same as returned decorator
548upon wrapped template fragment. Resulting template tag could be used as follows:
549
550.. code:: django
551
552    {% load mycachetags %}
553
554    {% cache_menu "top" %}
555        ... the top menu template code ...
556    {% endcache_menu %}
557
558    ... some template code ..
559
560    {% cache_menu "bottom" %}
561        ... the bottom menu template code ...
562    {% endcache_menu %}
563
564
565Jinja2 extension
566----------------
567
568Add ``cacheops.jinja2.cache`` to your extensions and use:
569
570.. code:: jinja
571
572    {% cached_as <queryset> [, timeout=<timeout>] [, extra=<key addition>] %}
573        ... some template code ...
574    {% endcached_as %}
575
576or
577
578.. code:: jinja
579
580    {% cached [timeout=<timeout>] [, extra=<key addition>] %}
581        ...
582    {% endcached %}
583
584Tags work the same way as corresponding decorators.
585
586
587Transactions
588------------
589
590Cacheops transparently supports transactions. This is implemented by following simple rules:
591
5921. 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.
593
5942. Any invalidating calls are scheduled to run on the outer commit of transaction.
595
5963. Savepoints and rollbacks are also handled appropriately.
597
598Mind that simple and file cache don't turn itself off in transactions but work as usual.
599
600
601Dog-pile effect prevention
602--------------------------
603
604There is optional locking mechanism to prevent several threads or processes simultaneously performing same heavy task. It works with ``@cached_as()`` and querysets:
605
606.. code:: python
607
608    @cached_as(qs, lock=True)
609    def heavy_func(...):
610        # ...
611
612    for item in qs.cache(lock=True):
613        # ...
614
615It is also possible to specify ``lock: True`` in ``CACHEOPS`` setting but that would probably be a waste. Locking has no overhead on cache hit though.
616
617
618Multiple database support
619-------------------------
620
621By default cacheops considers query result is same for same query, not depending
622on database queried. That could be changed with ``db_agnostic`` cache profile option:
623
624.. code:: python
625
626    CACHEOPS = {
627        'some.model': {'ops': 'get', 'db_agnostic': False, 'timeout': ...}
628    }
629
630
631Sharing redis instance
632----------------------
633
634Cacheops provides a way to share a redis instance by adding prefix to cache keys:
635
636.. code:: python
637
638    CACHEOPS_PREFIX = lambda query: ...
639    # or
640    CACHEOPS_PREFIX = 'some.module.cacheops_prefix'
641
642A most common usage would probably be a prefix by host name:
643
644.. code:: python
645
646    # get_request() returns current request saved to threadlocal by some middleware
647    cacheops_prefix = lambda _: get_request().get_host()
648
649A ``query`` object passed to callback also enables reflection on used databases and tables:
650
651.. code:: python
652
653    def cacheops_prefix(query):
654        query.dbs    # A list of databases queried
655        query.tables # A list of tables query is invalidated on
656
657        if set(query.tables) <= HELPER_TABLES:
658            return 'helper:'
659        if query.tables == ['blog_post']:
660            return 'blog:'
661
662**NOTE:** prefix is not used in simple and file cache. This might change in future cacheops.
663
664
665Custom serialization
666--------------------
667
668Cacheops uses ``pickle`` by default, employing it's default protocol. But you can specify your own
669it might be any module or a class having `.dumps()` and `.loads()` functions. For example you can use ``dill`` instead, which can serialize more things like anonymous functions:
670
671.. code:: python
672
673    CACHEOPS_SERIALIZER = 'dill'
674
675One less obvious use is to fix pickle protocol, to use cacheops cache across python versions:
676
677.. code:: python
678
679    import pickle
680
681    class CACHEOPS_SERIALIZER:
682        dumps = lambda data: pickle.dumps(data, 3)
683        loads = pickle.loads
684
685
686Using memory limit
687------------------
688
689If your cache never grows too large you may not bother. But if you do you have some options.
690Cacheops stores cached data along with invalidation data,
691so you can't just set ``maxmemory`` and let redis evict at its will.
692For now cacheops offers 2 imperfect strategies, which are considered **experimental**.
693So be careful and consider `leaving feedback <https://github.com/Suor/django-cacheops/issues/143>`_.
694
695First strategy is configuring ``maxmemory-policy volatile-ttl``. Invalidation data is guaranteed to have higher TTL than referenced keys.
696Redis however doesn't guarantee perfect TTL eviction order, it selects several keys and removes
697one with the least TTL, thus invalidator could be evicted before cache key it refers leaving it orphan and causing it survive next invalidation.
698You can reduce this chance by increasing ``maxmemory-samples`` redis config option and by reducing cache timeout.
699
700Second strategy, probably more efficient one is adding ``CACHEOPS_LRU = True`` to your settings and then using ``maxmemory-policy volatile-lru``.
701However, this makes invalidation structures persistent, they are still removed on associated events, but in absence of them can clutter redis database.
702
703
704Keeping stats
705-------------
706
707Cacheops provides ``cache_read`` and ``cache_invalidated`` signals for you to keep track.
708
709Cache read signal is emitted immediately after each cache lookup. Passed arguments are: ``sender`` - model class if queryset cache is fetched,
710``func`` - decorated function and ``hit`` - fetch success as boolean value.
711
712Here is a simple stats implementation:
713
714.. code:: python
715
716    from cacheops.signals import cache_read
717    from statsd.defaults.django import statsd
718
719    def stats_collector(sender, func, hit, **kwargs):
720        event = 'hit' if hit else 'miss'
721        statsd.incr('cacheops.%s' % event)
722
723    cache_read.connect(stats_collector)
724
725Cache invalidation signal is emitted after object, model or global invalidation passing ``sender`` and ``obj_dict`` args. 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.
726
727
728CAVEATS
729-------
730
7311. Conditions other than ``__exact``, ``__in`` and ``__isnull=True`` don't make invalidation
732   more granular.
7332. Conditions on TextFields, FileFields and BinaryFields don't make it either.
734   One should not test on their equality anyway. See `CACHEOPS_SKIP_FIELDS` though.
7353. Update of "selected_related" object does not invalidate cache for queryset.
736   Use ``.prefetch_related()`` instead.
7374. Mass updates don't trigger invalidation by default. But see ``.invalidated_update()``.
7385. Sliced queries are invalidated as non-sliced ones.
7396. Doesn't work with ``.raw()`` and other sql queries.
7407. Conditions on subqueries don't affect invalidation.
7418. Doesn't work right with multi-table inheritance.
742
743Here 1, 2, 3, 5 are part of the design compromise, trying to solve them will make
744things complicated and slow. 7 can be implemented if needed, but it's
745probably counter-productive since one can just break queries into simpler ones,
746which cache better. 4 is a deliberate choice, making it "right" will flush
747cache too much when update conditions are orthogonal to most queries conditions,
748see, however, `.invalidated_update()`. 8 is postponed until it will gain
749more interest or a champion willing to implement it emerges.
750
751All unsupported things could still be used easily enough with the help of ``@cached_as()``.
752
753
754Performance tips
755----------------
756
757Here come some performance tips to make cacheops and Django ORM faster.
758
7591. When you use cache you pickle and unpickle lots of django model instances, which could be slow. You can optimize django models serialization with `django-pickling <http://github.com/Suor/django-pickling>`_.
760
7612. Constructing querysets is rather slow in django, mainly because most of ``QuerySet`` methods 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::
762
763    items = Item.objects.inplace().filter(category=12).order_by('-date')[:20]
764
765   You can revert queryset to cloning state using ``.cloning()`` call.
766
767   Note that this is a micro-optimization technique. Using it is only desirable in the hottest places, not everywhere.
768
7693. 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.
770
7714. Run separate redis instance for cache with disabled `persistence <http://redis.io/topics/persistence>`_. You can manually call `SAVE <http://redis.io/commands/save>`_ or `BGSAVE <http://redis.io/commands/bgsave>`_ to stay hot upon server restart.
772
7735. 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.
774
775   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.
776
777
778Writing a test
779--------------
780
781Writing a test for an issue you are experiencing can speed up its resolution a lot.
782Here is how you do that. I suppose you have some application code causing it.
783
7841. Make a fork.
7852. Install all from ``requirements-test.txt``.
7863. Ensure you can run tests with ``./run_tests.py``.
7874. Copy relevant models code to ``tests/models.py``.
7885. Go to ``tests/tests.py`` and paste code causing exception to ``IssueTests.test_{issue_number}``.
7896. Execute ``./run_tests.py {issue_number}`` and see it failing.
7907. Cut down model and test code until error disappears and make a step back.
7918. Commit changes and make a pull request.
792
793
794TODO
795----
796
797- faster .get() handling for simple cases such as get by pk/id, with simple key calculation
798- integrate previous one with prefetch_related()
799- shard cache between multiple redises
800- respect subqueries?
801- respect headers in @cached_view*?
802- group invalidate_obj() calls?
803- a postpone invalidation context manager/decorator?
804- fast mode: store cache in local memory, but check in with redis if it's valid
805- an 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=?
806- custom cache eviction strategy in lua
807- cache a string directly (no pickle) for direct serving (custom key function?)
808
809
810.. |Build Status| image:: https://travis-ci.org/Suor/django-cacheops.svg?branch=master
811   :target: https://travis-ci.org/Suor/django-cacheops
812
813
814.. |Gitter| image:: https://badges.gitter.im/JoinChat.svg
815   :alt: Join the chat at https://gitter.im/Suor/django-cacheops
816   :target: https://gitter.im/Suor/django-cacheops?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
817