Debian Codegraph @

docs/quickstart.rst

raw
1 Quick start
2 -----------
3
4 Requirements
5 ............
6
7 - Django 4.2, 5.2, 6.0, 6.1
8 - Python 3.8-3.14
9 - a cache configured as ``'default'`` with one of these backends:
10
11 - `django-redis <https://github.com/niwinz/django-redis>`_
12 - `redis <https://docs.djangoproject.com/en/dev/topics/cache/#redis>`_
13 (requires Django >= 4)
14 - `memcached <https://docs.djangoproject.com/en/dev/topics/cache/#memcached>`_
15 (using either python-memcached or pylibmc)
16 - `filebased <https://docs.djangoproject.com/en/dev/topics/cache/#filesystem-caching>`_
17 - `locmem <https://docs.djangoproject.com/en/dev/topics/cache/#local-memory-caching>`_
18 (but it’s not shared between processes, see :ref:`locmem limits <Locmem>`)
19
20 - one of these databases:
21
22 - PostgreSQL
23 - SQLite
24 - MySQL (but on older versions like MySQL 5.5, django-cachalot has no effect,
25 see :ref:`MySQL limits <MySQL>`)
26
27 Usage
28 .....
29
30 #. ``pip install django-cachalot``
31 #. Add ``'cachalot',`` to your ``INSTALLED_APPS``
32 #. If you use multiple servers with a common cache server,
33 :ref:`double check their clock synchronisation <Multiple servers>`
34 #. If you modify data outside Django
35 – typically after restoring a SQL database –,
36 use the :ref:`manage.py command <Command>`
37 #. Be aware of :ref:`the few other limits <Limits>`
38 #. If you use
39 `django-debug-toolbar <https://github.com/jazzband/django-debug-toolbar>`_,
40 you can add ``'cachalot.panels.CachalotPanel',``
41 to your ``DEBUG_TOOLBAR_PANELS``
42 #. Enjoy!
43
44
45 .. _Settings:
46
47 Settings
48 ........
49
50 ``CACHALOT_ENABLED``
51 ~~~~~~~~~~~~~~~~~~~~
52
53 :Default: ``True``
54 :Description: If set to ``False``, disables SQL caching but keeps invalidating
55 to avoid stale cache.
56
57 ``CACHALOT_CACHE``
58 ~~~~~~~~~~~~~~~~~~
59
60 :Default: ``'default'``
61 :Description:
62 Alias of the cache from |CACHES|_ used by django-cachalot.
63
64 .. warning::
65 After modifying this setting, you should invalidate the cache
66 :ref:`using the manage.py command <Command>` or :ref:`the API <Api>`.
67 Indeed, only the cache configured using this setting is automatically
68 invalidated by django-cachalot – for optimisation reasons. So when you
69 change this setting, you end up on a cache that may contain stale data.
70
71 .. |CACHES| replace:: ``CACHES``
72 .. _CACHES: https://docs.djangoproject.com/en/dev/ref/settings/#caches
73
74 ``CACHALOT_DATABASES``
75 ~~~~~~~~~~~~~~~~~~~~~~
76
77 :Default: ``'supported_only'``
78 :Description:
79 List, tuple, set or frozenset of database aliases from |DATABASES|_ against
80 which django-cachalot will do caching. By default, the special value
81 ``'supported_only'`` enables django-cachalot only on supported database
82 engines.
83
84 .. |DATABASES| replace:: ``DATABASES``
85 .. _DATABASES: https://docs.djangoproject.com/en/dev/ref/settings/#databases
86
87 ``CACHALOT_USE_UNSUPPORTED_DATABASE``
88 ~~~~~~~~~~~~~~~~~~~~~~
89
90 :Default: ``False``
91 :Description:
92 Whether to allow usage of unsupported databases.
93 No startup errors will be thrown if this set to `True`.
94
95 ``CACHALOT_ADDITIONAL_SUPPORTED_DATABASES``
96 ~~~~~~~~~~~~~~~~~~~~~~
97
98 :Default: ``frozenset()``
99 :Description:
100 Allows us to define custom supported databases without setting
101 ``CACHALOT_USE_UNSUPPORTED_DATABASE`` to ``True``.
102
103 ``CACHALOT_TIMEOUT``
104 ~~~~~~~~~~~~~~~~~~~~
105
106 :Default: ``None``
107 :Description:
108 Number of seconds during which the cache should consider data as valid.
109 ``None`` means an infinite timeout.
110
111 .. warning::
112 Cache timeouts don’t work in a strict way on most cache backends.
113 A cache might not keep data during the requested timeout:
114 it can keep it in memory during a shorter time than the specified timeout.
115 It can even keep it longer, even if data is not returned when you request it.
116 So **don’t rely on timeouts to limit the size of your database**,
117 you might face some unexpected behaviour.
118 Always set the maximum cache size instead.
119
120 ``CACHALOT_CACHE_RANDOM``
121 ~~~~~~~~~~~~~~~~~~~~~~~~~
122
123 :Default: ``False``
124 :Description: If set to ``True``, caches random queries
125 (those with ``order_by('?')``).
126
127 ``CACHALOT_CACHE_ITERATORS``
128 ~~~~~~~~~~~~~~~~~~~~~~~~~
129
130 :Default: ``True``
131 :Description:
132 If set to ``True``, cache results from QuerySets that return
133 generators. This is useful for caching the result sets of QuerySets that
134 use ``.iterator()``.
135
136 .. warnings::
137 ``.iterator()`` is often used for large result sets. Caching these can use large
138 amounts of local memory because django-cachalot has to first convert them to a list to
139 store them in the cache. Setting to ``False`` can potentially resolve out of memory issues.
140
141 .. _CACHALOT_INVALIDATE_RAW:
142
143 ``CACHALOT_INVALIDATE_RAW``
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
145
146 :Default: ``True``
147 :Description:
148 If set to ``False``, disables automatic invalidation on raw
149 SQL queries – read :ref:`raw queries limits <Raw SQL queries>` for more info.
150
151
152 .. _CACHALOT_ONLY_CACHABLE_TABLES:
153
154 ``CACHALOT_ONLY_CACHABLE_TABLES``
155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
156
157 :Default: ``frozenset()``
158 :Description:
159 Sequence of SQL table names that will be the only ones django-cachalot
160 will cache. Only queries with a subset of these tables will be cached.
161 The sequence being empty (as it is by default) does not mean that no table
162 can be cached: it disables this setting, so any table can be cached.
163 :ref:`CACHALOT_UNCACHABLE_TABLES` has more weight than this:
164 if you add a table to both settings, it will never be cached.
165 Run ``./manage.py invalidate_cachalot`` after changing this setting.
166
167 ``CACHALOT_ONLY_CACHABLE_APPS``
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169
170 :Default: ``frozenset()``
171 :Description:
172 Sequence of Django apps whose associated models will be appended to
173 :ref:`CACHALOT_ONLY_CACHABLE_TABLES`. The rules between
174 :ref:`CACHALOT_UNCACHABLE_TABLES` and :ref:`CACHALOT_ONLY_CACHABLE_TABLES` still
175 apply as this setting only appends the given Django apps' tables on initial
176 Django setup.
177
178
179 .. _CACHALOT_UNCACHABLE_TABLES:
180
181 ``CACHALOT_UNCACHABLE_TABLES``
182 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
183
184 :Default: ``frozenset(('django_migrations',))``
185 :Description:
186 Sequence of SQL table names that will be ignored by django-cachalot.
187 Queries using a table mentioned in this setting will not be cached.
188 Always keep ``'django_migrations'`` in it, otherwise you may face
189 some issues, especially during tests.
190 Run ``./manage.py invalidate_cachalot`` after changing this setting.
191
192 ``CACHALOT_UNCACHABLE_APPS``
193 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
194
195 :Default: ``frozenset()``
196 :Description:
197 Sequence of Django apps whose associated models will be appended to
198 :ref:`CACHALOT_UNCACHABLE_TABLES`. The rules between
199 :ref:`CACHALOT_UNCACHABLE_TABLES` and :ref:`CACHALOT_ONLY_CACHABLE_TABLES` still
200 apply as this setting only appends the given Django apps' tables on initial
201 Django setup.
202
203 ``CACHALOT_ADDITIONAL_TABLES``
204 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
205
206 :Default: ``list()``
207 :Description:
208 Sequence of SQL table names that are not included in your Django
209 apps such as unmanaged models. Cachalot caches models that Django
210 does not manage, so if you want to ignore/not-cache those models,
211 then add them here.
212
213 ``CACHALOT_QUERY_KEYGEN``
214 ~~~~~~~~~~~~~~~~~~~~~~~~~
215
216 :Default: ``'cachalot.utils.get_query_cache_key'``
217 :Description: Python module path to the function that will be used to generate
218 the cache key of a SQL query.
219 Run ``./manage.py invalidate_cachalot``
220 after changing this setting.
221
222 ``CACHALOT_TABLE_KEYGEN``
223 ~~~~~~~~~~~~~~~~~~~~~~~~~
224
225 :Default: ``'cachalot.utils.get_table_cache_key'``
226 :Description: Python module path to the function that will be used to generate
227 the cache key of a SQL table.
228 Clear your cache after changing this setting (it’s not enough
229 to use ``./manage.py invalidate_cachalot``).
230
231 ``CACHALOT_FINAL_SQL_CHECK``
232 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
233
234 :Default: ``False``
235 :Description:
236 If set to ``True``, the final SQL check will be performed.
237 The `Final SQL check` checks for potentially overlooked tables when looking up involved tables
238 (eg. Ordering by referenced table). See tests for more details
239 (eg. ``test_order_by_field_of_another_table_with_check``).
240
241 Enabling this setting comes with a small performance cost::
242
243 CACHALOT_FINAL_SQL_CHECK=False:
244 mysql is 1.4× slower then 9.9× faster
245 postgresql is 1.3× slower then 11.7× faster
246 sqlite is 1.4× slower then 3.0× faster
247 filebased is 1.4× slower then 9.5× faster
248 locmem is 1.3× slower then 11.3× faster
249 pylibmc is 1.4× slower then 8.5× faster
250 pymemcache is 1.4× slower then 7.3× faster
251 redis is 1.4× slower then 6.8× faster
252
253 CACHALOT_FINAL_SQL_CHECK=True:
254 mysql is 1.5× slower then 9.0× faster
255 postgresql is 1.3× slower then 10.5× faster
256 sqlite is 1.4× slower then 2.6× faster
257 filebased is 1.4× slower then 9.1× faster
258 locmem is 1.3× slower then 9.9× faster
259 pylibmc is 1.4× slower then 7.5× faster
260 pymemcache is 1.4× slower then 6.5× faster
261 redis is 1.5× slower then 6.2× faster
262
263
264
265 .. _Command:
266
267 ``manage.py`` command
268 .....................
269
270 ``manage.py invalidate_cachalot`` is available to invalidate all the cache keys
271 set by django-cachalot. If you run it without any argument, it invalidates all
272 models on all caches and all databases. But you can specify what applications
273 or models are invalidated, and on which cache or database.
274
275 Examples:
276
277 ``./manage.py invalidate_cachalot auth``
278 Invalidates all models from the 'auth' application.
279 ``./manage.py invalidate_cachalot your_app auth.User``
280 Invalidates all models from the 'your_app' application, but also
281 the ``User`` model from the 'auth' application.
282 ``./manage.py invalidate_cachalot -c redis -p postgresql``
283 Invalidates all models,
284 but only for the database configured with the 'postgresql' alias,
285 and only for the cache configured with the 'redis' alias.
286
287
288 .. _Template utils:
289
290 Template utils
291 ..............
292
293 `Caching template fragments <https://docs.djangoproject.com/en/dev/topics/cache/#template-fragment-caching>`_
294 can be extremely powerful to speedup a Django application. However, it often
295 means you have to adapt your models to get a relevant cache key, typically
296 by adding a timestamp that refers to the last modification of the object.
297
298 But modifying your models and caching template fragments leads
299 to stale contents most of the time. There’s a simple reason to that: we rarely
300 only display the data from one model, we often want to display related data,
301 such as the number of books written by someone, display a quote from a book
302 of this author, display similar authors, etc. In such situations,
303 **it’s impossible to cache template fragments and avoid stale rendered data**.
304
305 Fortunately, django-cachalot provides an easy way to fix this issue,
306 by simply checking when was the last time data changed in the given models
307 or tables. The API function
308 :meth:`get_last_invalidation <cachalot.api.get_last_invalidation>` does that,
309 and we provided a ``get_last_invalidation`` template tag to directly
310 use it in templates. It works exactly the same as the API function.
311
312 Django template tag
313 ~~~~~~~~~~~~~~~~~~~
314
315 Example of a quite heavy nested loop with a lot of SQL queries
316 (considering no prefetch has been done)::
317
318 {% load cachalot cache %}
319
320 {% get_last_invalidation 'auth.User' 'library.Book' 'library.Author' as last_invalidation %}
321 {% cache 3600 short_user_profile last_invalidation %}
322 {{ user }} has borrowed these books:
323 {% for book in user.borrowed_books.all %}
324 <div class="book">
325 {{ book }} ({{ book.pages.count }} pages)
326 <span class="authors">
327 {% for author in book.authors.all %}
328 {{ author }}{% if not forloop.last %},{% endif %}
329 {% endfor %}
330 </span>
331 </div>
332 {% endfor %}
333 {% endcache %}
334
335 ``cache_alias`` and ``db_alias`` keywords arguments of this template tag
336 are also available (see
337 :meth:`cachalot.api.get_last_invalidation`).
338
339 Jinja2 statement and function
340 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
341
342 A Jinja2 extension for django-cachalot can be used, simply add
343 ``'cachalot.jinja2ext.cachalot',`` to the ``'extensions'`` list of the ``OPTIONS``
344 dict in the Django ``TEMPLATES`` settings.
345
346 It provides:
347
348 - The API function
349 :meth:`get_last_invalidation <cachalot.api.get_last_invalidation>` directly
350 available as a function anywhere in Jinja2.
351 - An Jinja2 statement equivalent to the ``cache`` template tag of Django.
352
353 The ``cache`` does the same thing as its Django template equivalent,
354 except that ``cache_key`` and ``timeout`` are optional keyword arguments, and
355 you need to add commas between arguments. When unspecified, ``cache_key`` is
356 generated from the template filename plus the statement line number, and
357 ``timeout`` defaults to infinite. To specify which cache should store the
358 saved content, use the ``cache_alias`` keyword argument.
359
360 Same example than above, but for Jinja2::
361
362 {% cache get_last_invalidation('auth.User', 'library.Book', 'library.Author'),
363 cache_key='short_user_profile', timeout=3600 %}
364 {{ user }} has borrowed these books:
365 {% for book in user.borrowed_books.all() %}
366 <div class="book">
367 {{ book }} ({{ book.pages.count() }} pages)
368 <span class="authors">
369 {% for author in book.authors.all() %}
370 {{ author }}{% if not loop.last %},{% endif %}
371 {% endfor %}
372 </span>
373 </div>
374 {% endfor %}
375 {% endcache %}
376
377
378 .. _Signal:
379
380 Signal
381 ......
382
383 ``cachalot.signals.post_invalidation`` is available if you need to do something
384 just after a cache invalidation (when you modify something in a SQL table).
385 ``sender`` is the name of the SQL table invalidated, and a keyword argument
386 ``db_alias`` explains which database is affected by the invalidation.
387 Be careful when you specify ``sender``, as it is sensible to string type.
388 To be sure, use ``Model._meta.db_table``.
389
390 This signal is not directly triggered during transactions,
391 it waits until the current transaction ends. This signal is also triggered
392 when invalidating using the API or the ``manage.py`` command. Be careful
393 when using multiple databases, if you invalidate all databases by simply
394 calling ``invalidate()``, this signal will be triggered one time
395 for each database and for each model. If you have 3 databases and 20 models,
396 ``invalidate()`` will trigger the signal 60 times.
397
398 Example:
399
400 .. code:: python
401
402 from cachalot.signals import post_invalidation
403 from django.dispatch import receiver
404 from django.core.mail import mail_admins
405 from django.contrib.auth import *
406
407 # This prints a message to the console after each table invalidation
408 def invalidation_debug(sender, **kwargs):
409 db_alias = kwargs['db_alias']
410 print('%s was invalidated in the DB configured as %s'
411 % (sender, db_alias))
412
413 post_invalidation.connect(invalidation_debug)
414
415 # Using the `receiver` decorator is just a nicer way
416 # to write the same thing as `signal.connect`.
417 # Here we specify `sender` so that the function is executed only if
418 # the table invalidated is the one specified.
419 # We also connect it several times to be executed for several senders.
420 @receiver(post_invalidation, sender=User.groups.through._meta.db_table)
421 @receiver(post_invalidation, sender=User.user_permissions.through._meta.db_table)
422 @receiver(post_invalidation, sender=Group.permissions.through._meta.db_table)
423 def warn_admin(sender, **kwargs):
424 mail_admins('User permissions changed',
425 'Someone probably gained or lost Django permissions.')