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