Debian Codegraph @

README.rst

raw
1 ====================
2 django-cache-memoize
3 ====================
4
5 * License: MPL 2.0
6
7 .. image:: https://github.com/peterbe/django-cache-memoize/workflows/Python/badge.svg
8 :alt: Build Status
9 :target: https://github.com/peterbe/django-cache-memoize/actions?query=workflow%3APython
10
11 .. image:: https://readthedocs.org/projects/django-cache-memoize/badge/?version=latest
12 :alt: Documentation Status
13 :target: https://django-cache-memoize.readthedocs.io/en/latest/?badge=latest
14
15 .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
16 :target: https://github.com/ambv/black
17
18 Django utility for a memoization decorator that uses the Django cache framework.
19
20 For versions of Python and Django, check out `the tox.ini file`_.
21
22 .. _`the tox.ini file`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini
23
24 Key Features
25 ------------
26
27 * Memoized function calls can be invalidated.
28
29 * Works with non-trivial arguments and keyword arguments
30
31 * Insight into cache hits and cache missed with a callback.
32
33 * Ability to use as a "guard" for repeated execution when storing the function
34 result isn't important or needed.
35
36
37 Installation
38 ============
39
40 .. code-block:: python
41
42 pip install django-cache-memoize
43
44 Usage
45 =====
46
47 .. code-block:: python
48
49 # Import the decorator
50 from cache_memoize import cache_memoize
51
52 # Attach decorator to cacheable function with a timeout of 100 seconds.
53 @cache_memoize(100)
54 def expensive_function(start, end):
55 return random.randint(start, end)
56
57 # Just a regular Django view
58 def myview(request):
59 # If you run this view repeatedly you'll get the same
60 # output every time for 100 seconds.
61 return http.HttpResponse(str(expensive_function(0, 100)))
62
63
64 The caching uses `Django's default cache framework`_. Ultimately, it calls
65 ``django.core.cache.cache.set(cache_key, function_out, expiration)``.
66 So if you have a function that returns something that can't be pickled and
67 cached it won't work.
68
69 For cases like this, Django exposes a simple, low-level cache API. You can
70 use this API to store objects in the cache with any level of granularity
71 you like. You can cache any Python object that can be pickled safely:
72 strings, dictionaries, lists of model objects, and so forth. (Most
73 common Python objects can be pickled; refer to the Python documentation
74 for more information about pickling.)
75
76 See `documentation`_.
77
78
79 .. _`Django's default cache framework`: https://docs.djangoproject.com/en/1.11/topics/cache/
80 .. _`documentation`: https://docs.djangoproject.com/en/1.11/topics/cache/#the-low-level-cache-api
81
82
83 Example Usage
84 =============
85
86 This blog post: `How to use django-cache-memoize`_
87
88 It demonstrates similarly to the above Usage example but with a little more
89 detail. In particular it demonstrates the difference between *not* using
90 ``django-cache-memoize`` and then adding it to your code after.
91
92 .. _`How to use django-cache-memoize`: https://www.peterbe.com/plog/how-to-use-django-cache-memoize
93
94 Advanced Usage
95 ==============
96
97 ``args_rewrite``
98 ~~~~~~~~~~~~~~~~
99
100 Internally the decorator rewrites every argument and keyword argument to
101 the function it wraps into a concatenated string. The first thing you
102 might want to do is help the decorator rewrite the arguments to something
103 more suitable as a cache key string. For example, suppose you have instances
104 of a class whose ``__str__`` method doesn't return a unique value. For example:
105
106 .. code-block:: python
107
108 class Record(models.Model):
109 name = models.CharField(max_length=100)
110 lastname = models.CharField(max_length=100)
111 friends = models.ManyToManyField(SomeOtherModel)
112
113 def __str__(self):
114 return self.name
115
116 # Example use:
117 >>> record = Record.objects.create(name='Peter', lastname='Bengtsson')
118 >>> print(record)
119 Peter
120 >>> record2 = Record.objects.create(name='Peter', lastname='Different')
121 >>> print(record2)
122 Peter
123
124 This is a contrived example, but basically *you know* that the ``str()``
125 conversion of certain arguments isn't safe. Then you can pass in a callable
126 called ``args_rewrite``. It gets the same positional and keyword arguments
127 as the function you're decorating. Here's an example implementation:
128
129 .. code-block:: python
130
131 from cache_memoize import cache_memoize
132
133 def count_friends_args_rewrite(record):
134 # The 'id' is always unique. Use that instead of the default __str__
135 return record.id
136
137 @cache_memoize(100, args_rewrite=count_friends_args_rewrite)
138 def count_friends(record):
139 # Assume this is an expensive function that can be memoize cached.
140 return record.friends.all().count()
141
142
143 ``prefix``
144 ~~~~~~~~~~
145
146 By default the prefix becomes the name of the function. Consider:
147
148 .. code-block:: python
149
150 from cache_memoize import cache_memoize
151
152 @cache_memoize(10, prefix='randomness')
153 def function1():
154 return random.random()
155
156 @cache_memoize(10, prefix='randomness')
157 def function2(): # different name, same arguments, same functionality
158 return random.random()
159
160 # Example use
161 >>> function1()
162 0.39403406043780986
163 >>> function1()
164 0.39403406043780986
165 >>> # ^ repeated of course
166 >>> function2()
167 0.39403406043780986
168 >>> # ^ because the prefix was forcibly the same, the cache key is the same
169
170
171 ``hit_callable``
172 ~~~~~~~~~~~~~~~~
173
174 If set, a function that gets called with the original argument and keyword
175 arguments **if** the cache was able to find and return a cache hit.
176 For example, suppose you want to tell your ``statsd`` server every time
177 there's a cache hit.
178
179 .. code-block:: python
180
181 from cache_memoize import cache_memoize
182
183 def _cache_hit(user, **kwargs):
184 statsdthing.incr(f'cachehit:{user.id}', 1)
185
186 @cache_memoize(10, hit_callable=_cache_hit)
187 def calculate_tax(user, tax=0.1):
188 return ...
189
190
191 ``miss_callable``
192 ~~~~~~~~~~~~~~~~~
193
194 Exact same functionality as ``hit_callable`` except the obvious difference
195 that it gets called if it was *not* a cache hit.
196
197 ``store_result``
198 ~~~~~~~~~~~~~~~~
199
200 This is useful if you have a function you want to make sure only gets called
201 once per timeout expiration but you don't actually care that much about
202 what the function return value was. Perhaps because you know that the
203 function returns something that would quickly fill up your ``memcached`` or
204 perhaps you know it returns something that can't be pickled. Then you
205 can set ``store_result`` to ``False``. This is equivalent to your function
206 returning ``True``.
207
208 .. code-block:: python
209
210 from cache_memoize import cache_memoize
211
212 @cache_memoize(1000, store_result=False)
213 def send_tax_returns(user):
214 # something something time consuming
215 ...
216 return some_none_pickleable_thing
217
218 def myview(request):
219 # View this view as much as you like the 'send_tax_returns' function
220 # won't be called more than once every 1000 seconds.
221 send_tax_returns(request.user)
222
223 ``cache_exceptions``
224 ~~~~~~~~~~~~~~~~~~~~
225
226 This is useful if you have a function that can raise an exception as valid
227 result. If the cached function raises any of specified exceptions is the
228 exception cached and raised as normal. Subsequent cached calls will
229 immediately re-raise the exception and the function will not be executed.
230 ``cache_exceptions`` accepts an Exception or a tuple of Exceptions.
231
232
233 This option allows you to cache said exceptions like any other result.
234 Only exceptions raised from the list of classes provided as cache_exceptions
235 are cached, all others are propagated immediately.
236
237 .. code-block:: python
238
239 >>> from cache_memoize import cache_memoize
240
241 >>> class InvalidParameter(Exception):
242 ... pass
243
244 >>> @cache_memoize(1000, cache_exceptions=(InvalidParameter, ))
245 ... def run_calculations(parameter):
246 ... # something something time consuming
247 ... raise InvalidParameter
248
249 >>> run_calculations(1)
250 Traceback (most recent call last):
251 ...
252 InvalidParameter
253
254 # run_calculations will now raise InvalidParameter immediately
255 # without running the expensive calculation
256 >>> run_calculations(1)
257 Traceback (most recent call last):
258 ...
259 InvalidParameter
260
261 ``cache_alias``
262 ~~~~~~~~~~~~~~~
263
264 The ``cache_alias`` argument allows you to use a cache other than the default.
265
266 .. code-block:: python
267
268 # Given settings like:
269 # CACHES = {
270 # 'default': {...},
271 # 'other': {...},
272 # }
273
274 @cache_memoize(1000, cache_alias='other')
275 def myfunc(start, end):
276 return random.random()
277
278
279 Cache invalidation
280 ~~~~~~~~~~~~~~~~~~
281
282 When you want to "undo" some caching done, you simply call the function
283 again with the same arguments except you add ``.invalidate`` to the function.
284
285 .. code-block:: python
286
287 from cache_memoize import cache_memoize
288
289 @cache_memoize(10)
290 def expensive_function(start, end):
291 return random.randint(start, end)
292
293 >>> expensive_function(1, 100)
294 65
295 >>> expensive_function(1, 100)
296 65
297 >>> expensive_function(100, 200)
298 121
299 >>> exensive_function.invalidate(1, 100)
300 >>> expensive_function(1, 100)
301 89
302 >>> expensive_function(100, 200)
303 121
304
305 An "alias" of doing the same thing is to pass a keyword argument called
306 ``_refresh=True``. Like this:
307
308 .. code-block:: python
309
310 # Continuing from the code block above
311 >>> expensive_function(100, 200)
312 121
313 >>> expensive_function(100, 200, _refresh=True)
314 177
315 >>> expensive_function(100, 200)
316 177
317
318 There is no way to clear more than one cache key. In the above example,
319 you had to know the "original arguments" when you wanted to invalidate
320 the cache. There is no method "search" for all cache keys that match a
321 certain pattern.
322
323
324 Compatibility
325 =============
326
327 * Python 3.8, 3.9, 3.10 & 3.11
328
329 * Django 3.2, 4.1 & 4.2
330
331 Check out the `tox.ini`_ file for more up-to-date compatibility by
332 test coverage.
333
334 .. _`tox.ini`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini
335
336 Prior Art
337 =========
338
339 History
340 ~~~~~~~
341
342 `Mozilla Symbol Server`_ is written in Django. It's a web service that
343 sits between C++ debuggers and AWS S3. It shuffles symbol files in and out of
344 AWS S3. Symbol files are for C++ (and other compiled languages) what
345 sourcemaps are for JavaScript.
346
347 This service gets a LOT of traffic. The download traffic (proxying requests
348 for symbols in S3) gets about ~40 requests per second. Due to the nature
349 of the application most of these GETs result in a 404 Not Found but instead
350 of asking AWS S3 for every single file, these lookups are cached in a
351 highly configured `Redis`_ configuration. This Redis cache is also connected
352 to the part of the code that uploads new files.
353
354 New uploads are arriving as zip file bundles of files, from Mozilla's build
355 systems, at a rate of about 600MB every minute, each containing on average
356 about 100 files each. When a new upload comes in we need to quickly be able
357 find out if it exists in S3 and this gets cached since often the same files
358 are repeated in different uploads. But when a file does get uploaded into S3
359 we need to quickly and confidently invalidate any local caches. That way you
360 get to keep a really aggressive cache without any stale periods.
361
362 This is the use case ``django-cache-memoize`` was built for and tested in.
363 It was originally written for Python 3.6 in Django 1.11 but when
364 extracted, made compatible with Python 2.7 and as far back as Django 1.8.
365
366 ``django-cache-memoize`` is also used in `SongSear.ch`_ to cache short
367 queries in the autocomplete search input. All autocomplete is done by
368 Elasticsearch, which is amazingly fast, but not as fast as ``memcached``.
369
370
371 .. _`Mozilla Symbol Server`: https://symbols.mozilla.org
372 .. _`Redis`: https://redis.io/
373 .. _`SongSear.ch`: https://songsear.ch
374
375
376 "Competition"
377 ~~~~~~~~~~~~~
378
379 There is already `django-memoize`_ by `Thomas Vavrys`_.
380 It too is available as a memoization decorator you use in Django. And it
381 uses the default cache framework as a storage. It used ``inspect`` on the
382 decorated function to build a cache key.
383
384 In benchmarks running both ``django-memoize`` and ``django-cache-memoize``
385 I found ``django-cache-memoize`` to be **~4 times faster** on average.
386
387 Another key difference is that ``django-cache-memoize`` uses ``str()`` and
388 ``django-memoize`` uses ``repr()`` which in certain cases of mutable objects
389 (e.g. class instances) as arguments the caching will not work. For example,
390 this does *not* work in ``django-memoize``:
391
392 .. code-block:: python
393
394 from memoize import memoize
395
396 @memoize(60)
397 def count_user_groups(user):
398 return user.groups.all().count()
399
400 def myview(request):
401 # this will never be memoized
402 print(count_user_groups(request.user))
403
404 However, this works...
405
406 .. code-block:: python
407
408 from cache_memoize import cache_memoize
409
410 @cache_memoize(60)
411 def count_user_groups(user):
412 return user.groups.all().count()
413
414 def myview(request):
415 # this *will* work as expected
416 print(count_user_groups(request.user))
417
418
419 .. _`django-memoize`: http://pythonhosted.org/django-memoize/
420 .. _`Thomas Vavrys`: https://github.com/tvavrys
421
422
423 Development
424 ===========
425
426 The most basic thing is to clone the repo and run:
427
428 .. code-block:: shell
429
430 pip install -e ".[dev]"
431 tox
432
433
434 Code style is all black
435 ~~~~~~~~~~~~~~~~~~~~~~~
436
437 All code has to be formatted with `Black <https://pypi.org/project/black/>`_
438 and the best tool for checking this is
439 `therapist <https://pypi.org/project/therapist/>`_ since it can help you run
440 all, help you fix things, and help you make sure linting is passing before
441 you git commit. This project also uses ``flake8`` to check other things
442 Black can't check.
443
444 To check linting with ``tox`` use:
445
446 .. code:: bash
447
448 tox -e lint-py36
449
450 To install the ``therapist`` pre-commit hook simply run:
451
452 .. code:: bash
453
454 therapist install
455
456 When you run ``therapist run`` it will only check the files you've touched.
457 To run it for all files use:
458
459 .. code:: bash
460
461 therapist run --use-tracked-files
462
463 And to fix all/any issues run:
464
465 .. code:: bash
466
467 therapist run --use-tracked-files --fix