././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734545330.5723658 django_cache_memoize-0.2.1/0000755000076500000240000000000014730607663015211 5ustar00peterbestaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1545921362.0 django_cache_memoize-0.2.1/AUTHORS.rst0000644000076500000240000000013413411161522017046 0ustar00peterbestaff- Peter Bengtsson (@peterbe) - Ben Spaulding (@benspaulding) - Eleni Lixourioti (@Geekfish) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1576677743.0 django_cache_memoize-0.2.1/LICENSE0000644000076500000240000004052613576430557016230 0ustar00peterbestaffMozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1734545330.571743 django_cache_memoize-0.2.1/PKG-INFO0000644000076500000240000003613314730607663016314 0ustar00peterbestaffMetadata-Version: 2.1 Name: django-cache-memoize Version: 0.2.1 Summary: Django utility for a memoization decorator that uses the Django cache framework. Home-page: https://github.com/peterbe/django-cache-memoize Author: Peter Bengtsson Author-email: mail@peterbe.com License: MPL-2.0 Keywords: django,memoize,cache,decorator Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment :: Mozilla Classifier: Framework :: Django Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Topic :: Internet :: WWW/HTTP Requires-Python: >=3.8 License-File: LICENSE License-File: AUTHORS.rst Provides-Extra: dev Requires-Dist: flake8; extra == "dev" Requires-Dist: tox; extra == "dev" Requires-Dist: twine; extra == "dev" Requires-Dist: therapist; extra == "dev" Requires-Dist: black; extra == "dev" ==================== django-cache-memoize ==================== * License: MPL 2.0 .. image:: https://github.com/peterbe/django-cache-memoize/workflows/Python/badge.svg :alt: Build Status :target: https://github.com/peterbe/django-cache-memoize/actions?query=workflow%3APython .. image:: https://readthedocs.org/projects/django-cache-memoize/badge/?version=latest :alt: Documentation Status :target: https://django-cache-memoize.readthedocs.io/en/latest/?badge=latest .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black Django utility for a memoization decorator that uses the Django cache framework. For versions of Python and Django, check out `the tox.ini file`_. .. _`the tox.ini file`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini Key Features ------------ * Memoized function calls can be invalidated. * Works with non-trivial arguments and keyword arguments * Insight into cache hits and cache missed with a callback. * Ability to use as a "guard" for repeated execution when storing the function result isn't important or needed. Installation ============ .. code-block:: python pip install django-cache-memoize Usage ===== .. code-block:: python # Import the decorator from cache_memoize import cache_memoize # Attach decorator to cacheable function with a timeout of 100 seconds. @cache_memoize(100) def expensive_function(start, end): return random.randint(start, end) # Just a regular Django view def myview(request): # If you run this view repeatedly you'll get the same # output every time for 100 seconds. return http.HttpResponse(str(expensive_function(0, 100))) The caching uses `Django's default cache framework`_. Ultimately, it calls ``django.core.cache.cache.set(cache_key, function_out, expiration)``. So if you have a function that returns something that can't be pickled and cached it won't work. For cases like this, Django exposes a simple, low-level cache API. You can use this API to store objects in the cache with any level of granularity you like. You can cache any Python object that can be pickled safely: strings, dictionaries, lists of model objects, and so forth. (Most common Python objects can be pickled; refer to the Python documentation for more information about pickling.) See `documentation`_. .. _`Django's default cache framework`: https://docs.djangoproject.com/en/1.11/topics/cache/ .. _`documentation`: https://docs.djangoproject.com/en/1.11/topics/cache/#the-low-level-cache-api Example Usage ============= This blog post: `How to use django-cache-memoize`_ It demonstrates similarly to the above Usage example but with a little more detail. In particular it demonstrates the difference between *not* using ``django-cache-memoize`` and then adding it to your code after. .. _`How to use django-cache-memoize`: https://www.peterbe.com/plog/how-to-use-django-cache-memoize Advanced Usage ============== ``args_rewrite`` ~~~~~~~~~~~~~~~~ Internally the decorator rewrites every argument and keyword argument to the function it wraps into a concatenated string. The first thing you might want to do is help the decorator rewrite the arguments to something more suitable as a cache key string. For example, suppose you have instances of a class whose ``__str__`` method doesn't return a unique value. For example: .. code-block:: python class Record(models.Model): name = models.CharField(max_length=100) lastname = models.CharField(max_length=100) friends = models.ManyToManyField(SomeOtherModel) def __str__(self): return self.name # Example use: >>> record = Record.objects.create(name='Peter', lastname='Bengtsson') >>> print(record) Peter >>> record2 = Record.objects.create(name='Peter', lastname='Different') >>> print(record2) Peter This is a contrived example, but basically *you know* that the ``str()`` conversion of certain arguments isn't safe. Then you can pass in a callable called ``args_rewrite``. It gets the same positional and keyword arguments as the function you're decorating. Here's an example implementation: .. code-block:: python from cache_memoize import cache_memoize def count_friends_args_rewrite(record): # The 'id' is always unique. Use that instead of the default __str__ return record.id @cache_memoize(100, args_rewrite=count_friends_args_rewrite) def count_friends(record): # Assume this is an expensive function that can be memoize cached. return record.friends.all().count() ``prefix`` ~~~~~~~~~~ By default the prefix becomes the name of the function. Consider: .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(10, prefix='randomness') def function1(): return random.random() @cache_memoize(10, prefix='randomness') def function2(): # different name, same arguments, same functionality return random.random() # Example use >>> function1() 0.39403406043780986 >>> function1() 0.39403406043780986 >>> # ^ repeated of course >>> function2() 0.39403406043780986 >>> # ^ because the prefix was forcibly the same, the cache key is the same ``hit_callable`` ~~~~~~~~~~~~~~~~ If set, a function that gets called with the original argument and keyword arguments **if** the cache was able to find and return a cache hit. For example, suppose you want to tell your ``statsd`` server every time there's a cache hit. .. code-block:: python from cache_memoize import cache_memoize def _cache_hit(user, **kwargs): statsdthing.incr(f'cachehit:{user.id}', 1) @cache_memoize(10, hit_callable=_cache_hit) def calculate_tax(user, tax=0.1): return ... ``miss_callable`` ~~~~~~~~~~~~~~~~~ Exact same functionality as ``hit_callable`` except the obvious difference that it gets called if it was *not* a cache hit. ``store_result`` ~~~~~~~~~~~~~~~~ This is useful if you have a function you want to make sure only gets called once per timeout expiration but you don't actually care that much about what the function return value was. Perhaps because you know that the function returns something that would quickly fill up your ``memcached`` or perhaps you know it returns something that can't be pickled. Then you can set ``store_result`` to ``False``. This is equivalent to your function returning ``True``. .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(1000, store_result=False) def send_tax_returns(user): # something something time consuming ... return some_none_pickleable_thing def myview(request): # View this view as much as you like the 'send_tax_returns' function # won't be called more than once every 1000 seconds. send_tax_returns(request.user) ``cache_exceptions`` ~~~~~~~~~~~~~~~~~~~~ This is useful if you have a function that can raise an exception as valid result. If the cached function raises any of specified exceptions is the exception cached and raised as normal. Subsequent cached calls will immediately re-raise the exception and the function will not be executed. ``cache_exceptions`` accepts an Exception or a tuple of Exceptions. This option allows you to cache said exceptions like any other result. Only exceptions raised from the list of classes provided as cache_exceptions are cached, all others are propagated immediately. .. code-block:: python >>> from cache_memoize import cache_memoize >>> class InvalidParameter(Exception): ... pass >>> @cache_memoize(1000, cache_exceptions=(InvalidParameter, )) ... def run_calculations(parameter): ... # something something time consuming ... raise InvalidParameter >>> run_calculations(1) Traceback (most recent call last): ... InvalidParameter # run_calculations will now raise InvalidParameter immediately # without running the expensive calculation >>> run_calculations(1) Traceback (most recent call last): ... InvalidParameter ``cache_alias`` ~~~~~~~~~~~~~~~ The ``cache_alias`` argument allows you to use a cache other than the default. .. code-block:: python # Given settings like: # CACHES = { # 'default': {...}, # 'other': {...}, # } @cache_memoize(1000, cache_alias='other') def myfunc(start, end): return random.random() Cache invalidation ~~~~~~~~~~~~~~~~~~ When you want to "undo" some caching done, you simply call the function again with the same arguments except you add ``.invalidate`` to the function. .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(10) def expensive_function(start, end): return random.randint(start, end) >>> expensive_function(1, 100) 65 >>> expensive_function(1, 100) 65 >>> expensive_function(100, 200) 121 >>> exensive_function.invalidate(1, 100) >>> expensive_function(1, 100) 89 >>> expensive_function(100, 200) 121 An "alias" of doing the same thing is to pass a keyword argument called ``_refresh=True``. Like this: .. code-block:: python # Continuing from the code block above >>> expensive_function(100, 200) 121 >>> expensive_function(100, 200, _refresh=True) 177 >>> expensive_function(100, 200) 177 There is no way to clear more than one cache key. In the above example, you had to know the "original arguments" when you wanted to invalidate the cache. There is no method "search" for all cache keys that match a certain pattern. Compatibility ============= * Python 3.8, 3.9, 3.10 & 3.11 * Django 3.2, 4.1 & 4.2 Check out the `tox.ini`_ file for more up-to-date compatibility by test coverage. .. _`tox.ini`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini Prior Art ========= History ~~~~~~~ `Mozilla Symbol Server`_ is written in Django. It's a web service that sits between C++ debuggers and AWS S3. It shuffles symbol files in and out of AWS S3. Symbol files are for C++ (and other compiled languages) what sourcemaps are for JavaScript. This service gets a LOT of traffic. The download traffic (proxying requests for symbols in S3) gets about ~40 requests per second. Due to the nature of the application most of these GETs result in a 404 Not Found but instead of asking AWS S3 for every single file, these lookups are cached in a highly configured `Redis`_ configuration. This Redis cache is also connected to the part of the code that uploads new files. New uploads are arriving as zip file bundles of files, from Mozilla's build systems, at a rate of about 600MB every minute, each containing on average about 100 files each. When a new upload comes in we need to quickly be able find out if it exists in S3 and this gets cached since often the same files are repeated in different uploads. But when a file does get uploaded into S3 we need to quickly and confidently invalidate any local caches. That way you get to keep a really aggressive cache without any stale periods. This is the use case ``django-cache-memoize`` was built for and tested in. It was originally written for Python 3.6 in Django 1.11 but when extracted, made compatible with Python 2.7 and as far back as Django 1.8. ``django-cache-memoize`` is also used in `SongSear.ch`_ to cache short queries in the autocomplete search input. All autocomplete is done by Elasticsearch, which is amazingly fast, but not as fast as ``memcached``. .. _`Mozilla Symbol Server`: https://symbols.mozilla.org .. _`Redis`: https://redis.io/ .. _`SongSear.ch`: https://songsear.ch "Competition" ~~~~~~~~~~~~~ There is already `django-memoize`_ by `Thomas Vavrys`_. It too is available as a memoization decorator you use in Django. And it uses the default cache framework as a storage. It used ``inspect`` on the decorated function to build a cache key. In benchmarks running both ``django-memoize`` and ``django-cache-memoize`` I found ``django-cache-memoize`` to be **~4 times faster** on average. Another key difference is that ``django-cache-memoize`` uses ``str()`` and ``django-memoize`` uses ``repr()`` which in certain cases of mutable objects (e.g. class instances) as arguments the caching will not work. For example, this does *not* work in ``django-memoize``: .. code-block:: python from memoize import memoize @memoize(60) def count_user_groups(user): return user.groups.all().count() def myview(request): # this will never be memoized print(count_user_groups(request.user)) However, this works... .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(60) def count_user_groups(user): return user.groups.all().count() def myview(request): # this *will* work as expected print(count_user_groups(request.user)) .. _`django-memoize`: http://pythonhosted.org/django-memoize/ .. _`Thomas Vavrys`: https://github.com/tvavrys Development =========== The most basic thing is to clone the repo and run: .. code-block:: shell pip install -e ".[dev]" tox Code style is all black ~~~~~~~~~~~~~~~~~~~~~~~ All code has to be formatted with `Black `_ and the best tool for checking this is `therapist `_ since it can help you run all, help you fix things, and help you make sure linting is passing before you git commit. This project also uses ``flake8`` to check other things Black can't check. To check linting with ``tox`` use: .. code:: bash tox -e lint-py36 To install the ``therapist`` pre-commit hook simply run: .. code:: bash therapist install When you run ``therapist run`` it will only check the files you've touched. To run it for all files use: .. code:: bash therapist run --use-tracked-files And to fix all/any issues run: .. code:: bash therapist run --use-tracked-files --fix ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1694704611.0 django_cache_memoize-0.2.1/README.rst0000644000076500000240000003355014500621743016674 0ustar00peterbestaff==================== django-cache-memoize ==================== * License: MPL 2.0 .. image:: https://github.com/peterbe/django-cache-memoize/workflows/Python/badge.svg :alt: Build Status :target: https://github.com/peterbe/django-cache-memoize/actions?query=workflow%3APython .. image:: https://readthedocs.org/projects/django-cache-memoize/badge/?version=latest :alt: Documentation Status :target: https://django-cache-memoize.readthedocs.io/en/latest/?badge=latest .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black Django utility for a memoization decorator that uses the Django cache framework. For versions of Python and Django, check out `the tox.ini file`_. .. _`the tox.ini file`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini Key Features ------------ * Memoized function calls can be invalidated. * Works with non-trivial arguments and keyword arguments * Insight into cache hits and cache missed with a callback. * Ability to use as a "guard" for repeated execution when storing the function result isn't important or needed. Installation ============ .. code-block:: python pip install django-cache-memoize Usage ===== .. code-block:: python # Import the decorator from cache_memoize import cache_memoize # Attach decorator to cacheable function with a timeout of 100 seconds. @cache_memoize(100) def expensive_function(start, end): return random.randint(start, end) # Just a regular Django view def myview(request): # If you run this view repeatedly you'll get the same # output every time for 100 seconds. return http.HttpResponse(str(expensive_function(0, 100))) The caching uses `Django's default cache framework`_. Ultimately, it calls ``django.core.cache.cache.set(cache_key, function_out, expiration)``. So if you have a function that returns something that can't be pickled and cached it won't work. For cases like this, Django exposes a simple, low-level cache API. You can use this API to store objects in the cache with any level of granularity you like. You can cache any Python object that can be pickled safely: strings, dictionaries, lists of model objects, and so forth. (Most common Python objects can be pickled; refer to the Python documentation for more information about pickling.) See `documentation`_. .. _`Django's default cache framework`: https://docs.djangoproject.com/en/1.11/topics/cache/ .. _`documentation`: https://docs.djangoproject.com/en/1.11/topics/cache/#the-low-level-cache-api Example Usage ============= This blog post: `How to use django-cache-memoize`_ It demonstrates similarly to the above Usage example but with a little more detail. In particular it demonstrates the difference between *not* using ``django-cache-memoize`` and then adding it to your code after. .. _`How to use django-cache-memoize`: https://www.peterbe.com/plog/how-to-use-django-cache-memoize Advanced Usage ============== ``args_rewrite`` ~~~~~~~~~~~~~~~~ Internally the decorator rewrites every argument and keyword argument to the function it wraps into a concatenated string. The first thing you might want to do is help the decorator rewrite the arguments to something more suitable as a cache key string. For example, suppose you have instances of a class whose ``__str__`` method doesn't return a unique value. For example: .. code-block:: python class Record(models.Model): name = models.CharField(max_length=100) lastname = models.CharField(max_length=100) friends = models.ManyToManyField(SomeOtherModel) def __str__(self): return self.name # Example use: >>> record = Record.objects.create(name='Peter', lastname='Bengtsson') >>> print(record) Peter >>> record2 = Record.objects.create(name='Peter', lastname='Different') >>> print(record2) Peter This is a contrived example, but basically *you know* that the ``str()`` conversion of certain arguments isn't safe. Then you can pass in a callable called ``args_rewrite``. It gets the same positional and keyword arguments as the function you're decorating. Here's an example implementation: .. code-block:: python from cache_memoize import cache_memoize def count_friends_args_rewrite(record): # The 'id' is always unique. Use that instead of the default __str__ return record.id @cache_memoize(100, args_rewrite=count_friends_args_rewrite) def count_friends(record): # Assume this is an expensive function that can be memoize cached. return record.friends.all().count() ``prefix`` ~~~~~~~~~~ By default the prefix becomes the name of the function. Consider: .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(10, prefix='randomness') def function1(): return random.random() @cache_memoize(10, prefix='randomness') def function2(): # different name, same arguments, same functionality return random.random() # Example use >>> function1() 0.39403406043780986 >>> function1() 0.39403406043780986 >>> # ^ repeated of course >>> function2() 0.39403406043780986 >>> # ^ because the prefix was forcibly the same, the cache key is the same ``hit_callable`` ~~~~~~~~~~~~~~~~ If set, a function that gets called with the original argument and keyword arguments **if** the cache was able to find and return a cache hit. For example, suppose you want to tell your ``statsd`` server every time there's a cache hit. .. code-block:: python from cache_memoize import cache_memoize def _cache_hit(user, **kwargs): statsdthing.incr(f'cachehit:{user.id}', 1) @cache_memoize(10, hit_callable=_cache_hit) def calculate_tax(user, tax=0.1): return ... ``miss_callable`` ~~~~~~~~~~~~~~~~~ Exact same functionality as ``hit_callable`` except the obvious difference that it gets called if it was *not* a cache hit. ``store_result`` ~~~~~~~~~~~~~~~~ This is useful if you have a function you want to make sure only gets called once per timeout expiration but you don't actually care that much about what the function return value was. Perhaps because you know that the function returns something that would quickly fill up your ``memcached`` or perhaps you know it returns something that can't be pickled. Then you can set ``store_result`` to ``False``. This is equivalent to your function returning ``True``. .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(1000, store_result=False) def send_tax_returns(user): # something something time consuming ... return some_none_pickleable_thing def myview(request): # View this view as much as you like the 'send_tax_returns' function # won't be called more than once every 1000 seconds. send_tax_returns(request.user) ``cache_exceptions`` ~~~~~~~~~~~~~~~~~~~~ This is useful if you have a function that can raise an exception as valid result. If the cached function raises any of specified exceptions is the exception cached and raised as normal. Subsequent cached calls will immediately re-raise the exception and the function will not be executed. ``cache_exceptions`` accepts an Exception or a tuple of Exceptions. This option allows you to cache said exceptions like any other result. Only exceptions raised from the list of classes provided as cache_exceptions are cached, all others are propagated immediately. .. code-block:: python >>> from cache_memoize import cache_memoize >>> class InvalidParameter(Exception): ... pass >>> @cache_memoize(1000, cache_exceptions=(InvalidParameter, )) ... def run_calculations(parameter): ... # something something time consuming ... raise InvalidParameter >>> run_calculations(1) Traceback (most recent call last): ... InvalidParameter # run_calculations will now raise InvalidParameter immediately # without running the expensive calculation >>> run_calculations(1) Traceback (most recent call last): ... InvalidParameter ``cache_alias`` ~~~~~~~~~~~~~~~ The ``cache_alias`` argument allows you to use a cache other than the default. .. code-block:: python # Given settings like: # CACHES = { # 'default': {...}, # 'other': {...}, # } @cache_memoize(1000, cache_alias='other') def myfunc(start, end): return random.random() Cache invalidation ~~~~~~~~~~~~~~~~~~ When you want to "undo" some caching done, you simply call the function again with the same arguments except you add ``.invalidate`` to the function. .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(10) def expensive_function(start, end): return random.randint(start, end) >>> expensive_function(1, 100) 65 >>> expensive_function(1, 100) 65 >>> expensive_function(100, 200) 121 >>> exensive_function.invalidate(1, 100) >>> expensive_function(1, 100) 89 >>> expensive_function(100, 200) 121 An "alias" of doing the same thing is to pass a keyword argument called ``_refresh=True``. Like this: .. code-block:: python # Continuing from the code block above >>> expensive_function(100, 200) 121 >>> expensive_function(100, 200, _refresh=True) 177 >>> expensive_function(100, 200) 177 There is no way to clear more than one cache key. In the above example, you had to know the "original arguments" when you wanted to invalidate the cache. There is no method "search" for all cache keys that match a certain pattern. Compatibility ============= * Python 3.8, 3.9, 3.10 & 3.11 * Django 3.2, 4.1 & 4.2 Check out the `tox.ini`_ file for more up-to-date compatibility by test coverage. .. _`tox.ini`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini Prior Art ========= History ~~~~~~~ `Mozilla Symbol Server`_ is written in Django. It's a web service that sits between C++ debuggers and AWS S3. It shuffles symbol files in and out of AWS S3. Symbol files are for C++ (and other compiled languages) what sourcemaps are for JavaScript. This service gets a LOT of traffic. The download traffic (proxying requests for symbols in S3) gets about ~40 requests per second. Due to the nature of the application most of these GETs result in a 404 Not Found but instead of asking AWS S3 for every single file, these lookups are cached in a highly configured `Redis`_ configuration. This Redis cache is also connected to the part of the code that uploads new files. New uploads are arriving as zip file bundles of files, from Mozilla's build systems, at a rate of about 600MB every minute, each containing on average about 100 files each. When a new upload comes in we need to quickly be able find out if it exists in S3 and this gets cached since often the same files are repeated in different uploads. But when a file does get uploaded into S3 we need to quickly and confidently invalidate any local caches. That way you get to keep a really aggressive cache without any stale periods. This is the use case ``django-cache-memoize`` was built for and tested in. It was originally written for Python 3.6 in Django 1.11 but when extracted, made compatible with Python 2.7 and as far back as Django 1.8. ``django-cache-memoize`` is also used in `SongSear.ch`_ to cache short queries in the autocomplete search input. All autocomplete is done by Elasticsearch, which is amazingly fast, but not as fast as ``memcached``. .. _`Mozilla Symbol Server`: https://symbols.mozilla.org .. _`Redis`: https://redis.io/ .. _`SongSear.ch`: https://songsear.ch "Competition" ~~~~~~~~~~~~~ There is already `django-memoize`_ by `Thomas Vavrys`_. It too is available as a memoization decorator you use in Django. And it uses the default cache framework as a storage. It used ``inspect`` on the decorated function to build a cache key. In benchmarks running both ``django-memoize`` and ``django-cache-memoize`` I found ``django-cache-memoize`` to be **~4 times faster** on average. Another key difference is that ``django-cache-memoize`` uses ``str()`` and ``django-memoize`` uses ``repr()`` which in certain cases of mutable objects (e.g. class instances) as arguments the caching will not work. For example, this does *not* work in ``django-memoize``: .. code-block:: python from memoize import memoize @memoize(60) def count_user_groups(user): return user.groups.all().count() def myview(request): # this will never be memoized print(count_user_groups(request.user)) However, this works... .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(60) def count_user_groups(user): return user.groups.all().count() def myview(request): # this *will* work as expected print(count_user_groups(request.user)) .. _`django-memoize`: http://pythonhosted.org/django-memoize/ .. _`Thomas Vavrys`: https://github.com/tvavrys Development =========== The most basic thing is to clone the repo and run: .. code-block:: shell pip install -e ".[dev]" tox Code style is all black ~~~~~~~~~~~~~~~~~~~~~~~ All code has to be formatted with `Black `_ and the best tool for checking this is `therapist `_ since it can help you run all, help you fix things, and help you make sure linting is passing before you git commit. This project also uses ``flake8`` to check other things Black can't check. To check linting with ``tox`` use: .. code:: bash tox -e lint-py36 To install the ``therapist`` pre-commit hook simply run: .. code:: bash therapist install When you run ``therapist run`` it will only check the files you've touched. To run it for all files use: .. code:: bash therapist run --use-tracked-files And to fix all/any issues run: .. code:: bash therapist run --use-tracked-files --fix ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734545330.5724335 django_cache_memoize-0.2.1/setup.cfg0000644000076500000240000000004614730607663017032 0ustar00peterbestaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734544839.0 django_cache_memoize-0.2.1/setup.py0000644000076500000240000000262714730606707016730 0ustar00peterbestafffrom os import path from setuptools import setup, find_packages _here = path.dirname(__file__) setup( name="django-cache-memoize", version="0.2.1", description=( "Django utility for a memoization decorator that uses the Django " "cache framework." ), long_description=open(path.join(_here, "README.rst")).read(), author="Peter Bengtsson", author_email="mail@peterbe.com", license="MPL-2.0", url="https://github.com/peterbe/django-cache-memoize", packages=find_packages(where="src"), package_dir={"": "src"}, python_requires=">=3.8", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment :: Mozilla", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3 :: Only", "Topic :: Internet :: WWW/HTTP", ], keywords=["django", "memoize", "cache", "decorator"], zip_safe=False, extras_require={"dev": ["flake8", "tox", "twine", "therapist", "black"]}, ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734545330.5312958 django_cache_memoize-0.2.1/src/0000755000076500000240000000000014730607663016000 5ustar00peterbestaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734545330.5398078 django_cache_memoize-0.2.1/src/cache_memoize/0000755000076500000240000000000014730607663020570 5ustar00peterbestaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734544719.0 django_cache_memoize-0.2.1/src/cache_memoize/__init__.py0000644000076500000240000001672514730606517022711 0ustar00peterbestafffrom functools import wraps import itertools import json import inspect import hashlib from urllib.parse import quote from django.db import models from django.core.cache import caches, DEFAULT_CACHE_ALIAS from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.utils.encoding import force_bytes MARKER = object() def cache_memoize( timeout=DEFAULT_TIMEOUT, prefix=None, extra=None, args_rewrite=None, hit_callable=None, miss_callable=None, key_generator_callable=None, store_result=True, cache_exceptions=(), cache_alias=DEFAULT_CACHE_ALIAS, ): """Decorator for memoizing function calls where we use the "local cache" to store the result. :arg int timeout: Number of seconds to store the result if not None :arg string prefix: If None becomes the function name. :arg extra: Optional callable or serializable structure of key components cache should vary on. :arg function args_rewrite: Callable that rewrites the args first useful if your function needs nontrivial types but you know a simple way to re-represent them for the sake of the cache key. :arg function hit_callable: Gets executed if key was in cache. :arg function miss_callable: Gets executed if key was *not* in cache. :arg key_generator_callable: Custom cache key name generator. :arg bool store_result: If you know the result is not important, just that the cache blocked it from running repeatedly, set this to False. :arg Exception cache_exceptions: Accepts an Exception or a tuple of Exceptions. If the cached function raises any of these exceptions is the exception cached and raised as normal. Subsequent cached calls will immediately re-raise the exception and the function will not be executed. this tuple will be cached, all other will be propagated. :arg string cache_alias: The cache alias to use; defaults to 'default'. Usage:: @cache_memoize( 300, # 5 min args_rewrite=lambda user: user.email, hit_callable=lambda: print("Cache hit!"), miss_callable=lambda: print("Cache miss :("), ) def hash_user_email(user): dk = hashlib.pbkdf2_hmac('sha256', user.email, b'salt', 100000) return binascii.hexlify(dk) Or, when you don't actually need the result, useful if you know it's not valuable to store the execution result:: @cache_memoize( 300, # 5 min store_result=False, ) def send_email(email): somelib.send(email, subject="You rock!", ...) Also, whatever you do where things get cached, you can undo that. For example:: @cache_memoize(100) def callmeonce(arg1): print(arg1) callmeonce('peter') # will print 'peter' callmeonce('peter') # nothing printed callmeonce.invalidate('peter') callmeonce('peter') # will print 'peter' Suppose you know for good reason you want to bypass the cache and really let the decorator let you through you can set one extra keyword argument called `_refresh`. For example:: @cache_memoize(100) def callmeonce(arg1): print(arg1) callmeonce('peter') # will print 'peter' callmeonce('peter') # nothing printed callmeonce('peter', _refresh=True) # will print 'peter' If your cache depends on external state you can provide `extra` values:: @cache_memoize(100, extra={'version': 2}) def callmeonce(arg1): print(arg1) An `extra` argument can be callable or any serializable structure:: @cache_memoize(100, extra=lambda req: req.user.is_staff) def callmeonce(arg1): print(arg1) """ if args_rewrite is None: def noop(*args): return args args_rewrite = noop def obj_key(obj): if isinstance(obj, models.Model): return "%s.%s.%s" % (obj._meta.app_label, obj._meta.model_name, obj.pk) elif hasattr(obj, "build_absolute_uri"): return obj.build_absolute_uri() elif inspect.isfunction(obj): factors = [obj.__module__, obj.__name__] return factors else: return str(obj) def decorator(func): def _default_make_cache_key(*args, **kwargs): cache_key = ":".join( itertools.chain( (quote(str(x)) for x in args_rewrite(*args)), ( "{}={}".format(quote(k), quote(str(v))) for k, v in sorted(kwargs.items()) ), ) ) prefix_ = prefix or ".".join((func.__module__ or "", func.__qualname__)) extra_val = json.dumps( extra(*args, **kwargs) if callable(extra) else extra, sort_keys=True, default=obj_key, ) return hashlib.md5( force_bytes("cache_memoize" + prefix_ + cache_key + extra_val) ).hexdigest() _make_cache_key = key_generator_callable or _default_make_cache_key @wraps(func) def inner(*args, **kwargs): # The cache backend is fetched here (not in the outer decorator scope) # to guarantee thread-safety at runtime. cache = caches[cache_alias] # The cache key string should never be dependent on special keyword # arguments like _refresh. So extract it into a variable as soon as # possible. _refresh = bool(kwargs.pop("_refresh", False)) cache_key = _make_cache_key(*args, **kwargs) if _refresh: result = MARKER else: result = cache.get(cache_key, MARKER) if result is MARKER: # If the function all raises an exception we want to cache, # catch it, else let it propagate. try: result = func(*args, **kwargs) except cache_exceptions as exception: result = exception if not store_result: # Then the result isn't valuable/important to store but # we want to store something. Just to remember that # it has be done. cache.set(cache_key, True, timeout) else: cache.set(cache_key, result, timeout) if miss_callable: miss_callable(*args, **kwargs) elif hit_callable: hit_callable(*args, **kwargs) # If the result is an exception we've caught and cached, raise it # in the end as to not change the API of the function we're caching. if isinstance(result, Exception): raise result return result def invalidate(*args, **kwargs): # The cache backend is fetched here (not in the outer decorator scope) # to guarantee thread-safety at runtime. cache = caches[cache_alias] kwargs.pop("_refresh", None) cache_key = _make_cache_key(*args, **kwargs) cache.delete(cache_key) def get_cache_key(*args, **kwargs): kwargs.pop("_refresh", None) return _make_cache_key(*args, **kwargs) inner.invalidate = invalidate inner.get_cache_key = get_cache_key return inner return decorator ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734545330.5708735 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/0000755000076500000240000000000014730607663023604 5ustar00peterbestaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545330.0 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/PKG-INFO0000644000076500000240000003613314730607662024706 0ustar00peterbestaffMetadata-Version: 2.1 Name: django-cache-memoize Version: 0.2.1 Summary: Django utility for a memoization decorator that uses the Django cache framework. Home-page: https://github.com/peterbe/django-cache-memoize Author: Peter Bengtsson Author-email: mail@peterbe.com License: MPL-2.0 Keywords: django,memoize,cache,decorator Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment :: Mozilla Classifier: Framework :: Django Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Topic :: Internet :: WWW/HTTP Requires-Python: >=3.8 License-File: LICENSE License-File: AUTHORS.rst Provides-Extra: dev Requires-Dist: flake8; extra == "dev" Requires-Dist: tox; extra == "dev" Requires-Dist: twine; extra == "dev" Requires-Dist: therapist; extra == "dev" Requires-Dist: black; extra == "dev" ==================== django-cache-memoize ==================== * License: MPL 2.0 .. image:: https://github.com/peterbe/django-cache-memoize/workflows/Python/badge.svg :alt: Build Status :target: https://github.com/peterbe/django-cache-memoize/actions?query=workflow%3APython .. image:: https://readthedocs.org/projects/django-cache-memoize/badge/?version=latest :alt: Documentation Status :target: https://django-cache-memoize.readthedocs.io/en/latest/?badge=latest .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black Django utility for a memoization decorator that uses the Django cache framework. For versions of Python and Django, check out `the tox.ini file`_. .. _`the tox.ini file`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini Key Features ------------ * Memoized function calls can be invalidated. * Works with non-trivial arguments and keyword arguments * Insight into cache hits and cache missed with a callback. * Ability to use as a "guard" for repeated execution when storing the function result isn't important or needed. Installation ============ .. code-block:: python pip install django-cache-memoize Usage ===== .. code-block:: python # Import the decorator from cache_memoize import cache_memoize # Attach decorator to cacheable function with a timeout of 100 seconds. @cache_memoize(100) def expensive_function(start, end): return random.randint(start, end) # Just a regular Django view def myview(request): # If you run this view repeatedly you'll get the same # output every time for 100 seconds. return http.HttpResponse(str(expensive_function(0, 100))) The caching uses `Django's default cache framework`_. Ultimately, it calls ``django.core.cache.cache.set(cache_key, function_out, expiration)``. So if you have a function that returns something that can't be pickled and cached it won't work. For cases like this, Django exposes a simple, low-level cache API. You can use this API to store objects in the cache with any level of granularity you like. You can cache any Python object that can be pickled safely: strings, dictionaries, lists of model objects, and so forth. (Most common Python objects can be pickled; refer to the Python documentation for more information about pickling.) See `documentation`_. .. _`Django's default cache framework`: https://docs.djangoproject.com/en/1.11/topics/cache/ .. _`documentation`: https://docs.djangoproject.com/en/1.11/topics/cache/#the-low-level-cache-api Example Usage ============= This blog post: `How to use django-cache-memoize`_ It demonstrates similarly to the above Usage example but with a little more detail. In particular it demonstrates the difference between *not* using ``django-cache-memoize`` and then adding it to your code after. .. _`How to use django-cache-memoize`: https://www.peterbe.com/plog/how-to-use-django-cache-memoize Advanced Usage ============== ``args_rewrite`` ~~~~~~~~~~~~~~~~ Internally the decorator rewrites every argument and keyword argument to the function it wraps into a concatenated string. The first thing you might want to do is help the decorator rewrite the arguments to something more suitable as a cache key string. For example, suppose you have instances of a class whose ``__str__`` method doesn't return a unique value. For example: .. code-block:: python class Record(models.Model): name = models.CharField(max_length=100) lastname = models.CharField(max_length=100) friends = models.ManyToManyField(SomeOtherModel) def __str__(self): return self.name # Example use: >>> record = Record.objects.create(name='Peter', lastname='Bengtsson') >>> print(record) Peter >>> record2 = Record.objects.create(name='Peter', lastname='Different') >>> print(record2) Peter This is a contrived example, but basically *you know* that the ``str()`` conversion of certain arguments isn't safe. Then you can pass in a callable called ``args_rewrite``. It gets the same positional and keyword arguments as the function you're decorating. Here's an example implementation: .. code-block:: python from cache_memoize import cache_memoize def count_friends_args_rewrite(record): # The 'id' is always unique. Use that instead of the default __str__ return record.id @cache_memoize(100, args_rewrite=count_friends_args_rewrite) def count_friends(record): # Assume this is an expensive function that can be memoize cached. return record.friends.all().count() ``prefix`` ~~~~~~~~~~ By default the prefix becomes the name of the function. Consider: .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(10, prefix='randomness') def function1(): return random.random() @cache_memoize(10, prefix='randomness') def function2(): # different name, same arguments, same functionality return random.random() # Example use >>> function1() 0.39403406043780986 >>> function1() 0.39403406043780986 >>> # ^ repeated of course >>> function2() 0.39403406043780986 >>> # ^ because the prefix was forcibly the same, the cache key is the same ``hit_callable`` ~~~~~~~~~~~~~~~~ If set, a function that gets called with the original argument and keyword arguments **if** the cache was able to find and return a cache hit. For example, suppose you want to tell your ``statsd`` server every time there's a cache hit. .. code-block:: python from cache_memoize import cache_memoize def _cache_hit(user, **kwargs): statsdthing.incr(f'cachehit:{user.id}', 1) @cache_memoize(10, hit_callable=_cache_hit) def calculate_tax(user, tax=0.1): return ... ``miss_callable`` ~~~~~~~~~~~~~~~~~ Exact same functionality as ``hit_callable`` except the obvious difference that it gets called if it was *not* a cache hit. ``store_result`` ~~~~~~~~~~~~~~~~ This is useful if you have a function you want to make sure only gets called once per timeout expiration but you don't actually care that much about what the function return value was. Perhaps because you know that the function returns something that would quickly fill up your ``memcached`` or perhaps you know it returns something that can't be pickled. Then you can set ``store_result`` to ``False``. This is equivalent to your function returning ``True``. .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(1000, store_result=False) def send_tax_returns(user): # something something time consuming ... return some_none_pickleable_thing def myview(request): # View this view as much as you like the 'send_tax_returns' function # won't be called more than once every 1000 seconds. send_tax_returns(request.user) ``cache_exceptions`` ~~~~~~~~~~~~~~~~~~~~ This is useful if you have a function that can raise an exception as valid result. If the cached function raises any of specified exceptions is the exception cached and raised as normal. Subsequent cached calls will immediately re-raise the exception and the function will not be executed. ``cache_exceptions`` accepts an Exception or a tuple of Exceptions. This option allows you to cache said exceptions like any other result. Only exceptions raised from the list of classes provided as cache_exceptions are cached, all others are propagated immediately. .. code-block:: python >>> from cache_memoize import cache_memoize >>> class InvalidParameter(Exception): ... pass >>> @cache_memoize(1000, cache_exceptions=(InvalidParameter, )) ... def run_calculations(parameter): ... # something something time consuming ... raise InvalidParameter >>> run_calculations(1) Traceback (most recent call last): ... InvalidParameter # run_calculations will now raise InvalidParameter immediately # without running the expensive calculation >>> run_calculations(1) Traceback (most recent call last): ... InvalidParameter ``cache_alias`` ~~~~~~~~~~~~~~~ The ``cache_alias`` argument allows you to use a cache other than the default. .. code-block:: python # Given settings like: # CACHES = { # 'default': {...}, # 'other': {...}, # } @cache_memoize(1000, cache_alias='other') def myfunc(start, end): return random.random() Cache invalidation ~~~~~~~~~~~~~~~~~~ When you want to "undo" some caching done, you simply call the function again with the same arguments except you add ``.invalidate`` to the function. .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(10) def expensive_function(start, end): return random.randint(start, end) >>> expensive_function(1, 100) 65 >>> expensive_function(1, 100) 65 >>> expensive_function(100, 200) 121 >>> exensive_function.invalidate(1, 100) >>> expensive_function(1, 100) 89 >>> expensive_function(100, 200) 121 An "alias" of doing the same thing is to pass a keyword argument called ``_refresh=True``. Like this: .. code-block:: python # Continuing from the code block above >>> expensive_function(100, 200) 121 >>> expensive_function(100, 200, _refresh=True) 177 >>> expensive_function(100, 200) 177 There is no way to clear more than one cache key. In the above example, you had to know the "original arguments" when you wanted to invalidate the cache. There is no method "search" for all cache keys that match a certain pattern. Compatibility ============= * Python 3.8, 3.9, 3.10 & 3.11 * Django 3.2, 4.1 & 4.2 Check out the `tox.ini`_ file for more up-to-date compatibility by test coverage. .. _`tox.ini`: https://github.com/peterbe/django-cache-memoize/blob/master/tox.ini Prior Art ========= History ~~~~~~~ `Mozilla Symbol Server`_ is written in Django. It's a web service that sits between C++ debuggers and AWS S3. It shuffles symbol files in and out of AWS S3. Symbol files are for C++ (and other compiled languages) what sourcemaps are for JavaScript. This service gets a LOT of traffic. The download traffic (proxying requests for symbols in S3) gets about ~40 requests per second. Due to the nature of the application most of these GETs result in a 404 Not Found but instead of asking AWS S3 for every single file, these lookups are cached in a highly configured `Redis`_ configuration. This Redis cache is also connected to the part of the code that uploads new files. New uploads are arriving as zip file bundles of files, from Mozilla's build systems, at a rate of about 600MB every minute, each containing on average about 100 files each. When a new upload comes in we need to quickly be able find out if it exists in S3 and this gets cached since often the same files are repeated in different uploads. But when a file does get uploaded into S3 we need to quickly and confidently invalidate any local caches. That way you get to keep a really aggressive cache without any stale periods. This is the use case ``django-cache-memoize`` was built for and tested in. It was originally written for Python 3.6 in Django 1.11 but when extracted, made compatible with Python 2.7 and as far back as Django 1.8. ``django-cache-memoize`` is also used in `SongSear.ch`_ to cache short queries in the autocomplete search input. All autocomplete is done by Elasticsearch, which is amazingly fast, but not as fast as ``memcached``. .. _`Mozilla Symbol Server`: https://symbols.mozilla.org .. _`Redis`: https://redis.io/ .. _`SongSear.ch`: https://songsear.ch "Competition" ~~~~~~~~~~~~~ There is already `django-memoize`_ by `Thomas Vavrys`_. It too is available as a memoization decorator you use in Django. And it uses the default cache framework as a storage. It used ``inspect`` on the decorated function to build a cache key. In benchmarks running both ``django-memoize`` and ``django-cache-memoize`` I found ``django-cache-memoize`` to be **~4 times faster** on average. Another key difference is that ``django-cache-memoize`` uses ``str()`` and ``django-memoize`` uses ``repr()`` which in certain cases of mutable objects (e.g. class instances) as arguments the caching will not work. For example, this does *not* work in ``django-memoize``: .. code-block:: python from memoize import memoize @memoize(60) def count_user_groups(user): return user.groups.all().count() def myview(request): # this will never be memoized print(count_user_groups(request.user)) However, this works... .. code-block:: python from cache_memoize import cache_memoize @cache_memoize(60) def count_user_groups(user): return user.groups.all().count() def myview(request): # this *will* work as expected print(count_user_groups(request.user)) .. _`django-memoize`: http://pythonhosted.org/django-memoize/ .. _`Thomas Vavrys`: https://github.com/tvavrys Development =========== The most basic thing is to clone the repo and run: .. code-block:: shell pip install -e ".[dev]" tox Code style is all black ~~~~~~~~~~~~~~~~~~~~~~~ All code has to be formatted with `Black `_ and the best tool for checking this is `therapist `_ since it can help you run all, help you fix things, and help you make sure linting is passing before you git commit. This project also uses ``flake8`` to check other things Black can't check. To check linting with ``tox`` use: .. code:: bash tox -e lint-py36 To install the ``therapist`` pre-commit hook simply run: .. code:: bash therapist install When you run ``therapist run`` it will only check the files you've touched. To run it for all files use: .. code:: bash therapist run --use-tracked-files And to fix all/any issues run: .. code:: bash therapist run --use-tracked-files --fix ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545330.0 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/SOURCES.txt0000644000076500000240000000057714730607662025500 0ustar00peterbestaffAUTHORS.rst LICENSE README.rst setup.py src/cache_memoize/__init__.py src/django_cache_memoize.egg-info/PKG-INFO src/django_cache_memoize.egg-info/SOURCES.txt src/django_cache_memoize.egg-info/dependency_links.txt src/django_cache_memoize.egg-info/not-zip-safe src/django_cache_memoize.egg-info/requires.txt src/django_cache_memoize.egg-info/top_level.txt tests/test_cache_memoize.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545330.0 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/dependency_links.txt0000644000076500000240000000000114730607662027651 0ustar00peterbestaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1509135471.0 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/not-zip-safe0000644000076500000240000000000113174712157026026 0ustar00peterbestaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545330.0 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/requires.txt0000644000076500000240000000005014730607662026176 0ustar00peterbestaff [dev] flake8 tox twine therapist black ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545330.0 django_cache_memoize-0.2.1/src/django_cache_memoize.egg-info/top_level.txt0000644000076500000240000000001614730607662026332 0ustar00peterbestaffcache_memoize ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1734545330.569827 django_cache_memoize-0.2.1/tests/0000755000076500000240000000000014730607663016353 5ustar00peterbestaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734355941.0 django_cache_memoize-0.2.1/tests/test_cache_memoize.py0000644000076500000240000003426114730025745022555 0ustar00peterbestaff# -*- coding: utf-8 -*- import random from threading import Thread, Lock import pytest from django.core.cache import cache from cache_memoize import cache_memoize from .dummy_package import a as dummy_a from .dummy_package import b as dummy_b def test_the_setup(): """If this doesn't work, the settings' CACHES isn't working.""" cache.set("foo", "bar", 1) assert cache.get("foo") == "bar" def test_cache_memoize(): calls_made = [] @cache_memoize(10) def runmeonce(a, b, k1="bla", k2=None): calls_made.append((a, b, k1, k2)) return "{} {} {} {}".format(a, b, k1, k2) # sample implementation runmeonce(1, 2) runmeonce(1, 2) assert len(calls_made) == 1 runmeonce(1, 3) assert len(calls_made) == 2 # Should work with most basic types runmeonce(1.1, "foo") runmeonce(1.1, "foo") assert len(calls_made) == 3 # Even more "advanced" types runmeonce(1.1, "foo", k1=list("åäö")) runmeonce(1.1, "foo", k1=list("åäö")) assert len(calls_made) == 4 # And shouldn't be a problem even if the arguments are really long runmeonce("A" * 200, "B" * 200, {"C" * 100: "D" * 100}) assert len(calls_made) == 5 # The order of the keyword arguments doesn't matter runmeonce(1, 2, k1=3, k2=4) runmeonce(1, 2, k2=4, k1=3) assert len(calls_made) == 6 @pytest.mark.parametrize( ("obj_1", "obj_2"), [ # Check identically named entities from different modules (dummy_a.func, dummy_b.func), (dummy_a.decorated_func, dummy_b.decorated_func), (dummy_a.DummyClass().func, dummy_b.DummyClass().func), (dummy_a.DummyClass().decorated_func, dummy_b.DummyClass().decorated_func), # # Check identically named entities from different scopes (dummy_a.func, dummy_a.DummyClass().func), (dummy_a.func, dummy_a.func_factory()), # # Check decorated entities (dummy_a.decorated_func, dummy_a.another_decorated_func), ( dummy_a.DummyClass().decorated_func, dummy_a.DummyClass().another_decorated_func, ), ], ) def test_default_prefix_uniqueness(obj_1, obj_2): assert obj_1.get_cache_key() != obj_2.get_cache_key() def test_prefixes(): calls_made = [] # different prefixes @cache_memoize(10, prefix="first") def foo(value): calls_made.append(value) return "ho" @cache_memoize(10, prefix="second") def bar(value): calls_made.append(value) return "ho" foo("hey") assert len(calls_made) == 1 bar("hey") assert len(calls_made) == 2 def test_no_store_result(): calls_made = [] # Test when you don't care about the result @cache_memoize(10, store_result=False, prefix="different") def returnnothing(a, b, k="bla"): calls_made.append((a, b, k)) # note it returns None returnnothing(1, 2) returnnothing(1, 2) assert len(calls_made) == 1 class TestDefaultCacheKeyQuoting: @pytest.mark.parametrize( "bits", [("a", "b", "c"), ("ä", "á", "ö"), ("ë".encode(), b"\02", b"i")] ) def test_colons_quoting(self, bits): calls_made = [] @cache_memoize(10) def fun(a, b, k="bla"): calls_made.append((a, b, k)) return (a, b, k) sep = ":" if isinstance(bits[0], bytes): sep = sep.encode() a1, a2 = (sep.join(bits[:2]), bits[2]) b1, b2 = (bits[0], sep.join(bits[1:])) fun(a1, a2) fun(b1, b2) assert len(calls_made) == 2 @pytest.mark.parametrize( ("arguments_1", "arguments_2"), [ ( (("a", "b", "c"), {}), (("a:b:c",), {}), ), ( (("a", "b"), {"c": "d"}), (("a",), {"b:c": "d"}), ), ( (("a",), {"b": "c"}), (("a", "b=c"), {}), ), ( ((), {"a": "b=c"}), ((), {"a=b": "c"}), ), ], ) def test_general_quoting(self, arguments_1, arguments_2): calls_made = [] @cache_memoize(10) def fun(*args, **kwargs): calls_made.append((args, kwargs)) args, kwargs = arguments_1 fun(*args, **kwargs) args, kwargs = arguments_2 fun(*args, **kwargs) assert calls_made == [arguments_1, arguments_2] def test_cache_memoize_hit_miss_callables(): hits = [] misses = [] calls_made = [] def hit_callable(arg): hits.append(arg) def miss_callable(arg): misses.append(arg) @cache_memoize(10, hit_callable=hit_callable, miss_callable=miss_callable) def runmeonce(arg): calls_made.append(arg) return arg * 2 result = runmeonce(100) assert result == 200 assert len(calls_made) == 1 assert len(hits) == 0 assert len(misses) == 1 result = runmeonce(100) assert result == 200 assert len(calls_made) == 1 assert len(hits) == 1 assert len(misses) == 1 result = runmeonce(100) assert result == 200 assert len(calls_made) == 1 assert len(hits) == 2 assert len(misses) == 1 result = runmeonce(200) assert result == 400 assert len(calls_made) == 2 assert len(hits) == 2 assert len(misses) == 2 def test_cache_memoize_refresh(): calls_made = [] @cache_memoize(10) def runmeonce(a): calls_made.append(a) return a * 2 runmeonce(10) assert len(calls_made) == 1 runmeonce(10) assert len(calls_made) == 1 runmeonce(10, _refresh=True) assert len(calls_made) == 2 def test_cache_memoize_different_functions_same_arguments(): calls_made_1 = [] calls_made_2 = [] @cache_memoize(10) def function_1(a): calls_made_1.append(a) return a * 2 @cache_memoize(10) def function_2(a): calls_made_2.append(a) return a * 3 assert function_1(100) == 200 assert len(calls_made_1) == 1 assert function_1(100) == 200 assert len(calls_made_1) == 1 # Same arguments but to different function assert function_2(100) == 300 assert len(calls_made_1) == 1 assert len(calls_made_2) == 1 assert function_2(100) == 300 assert len(calls_made_1) == 1 assert len(calls_made_2) == 1 assert function_2(1000) == 3000 assert len(calls_made_1) == 1 assert len(calls_made_2) == 2 # If you set the prefix, you can cross wire functions. # Note sure why you'd ever want to do this though @cache_memoize( 10, prefix=".".join((function_2.__module__, function_2.__qualname__)) ) def function_3(a): raise Exception assert function_3(100) == 300 def test_invalidate(): calls_made = [] @cache_memoize(10) def function(argument): calls_made.append(argument) return random.random() value = function(100) assert value == function(100) assert len(calls_made) == 1 function.invalidate(999) # different args assert value == function(100) assert len(calls_made) == 1 function.invalidate(100) # known args assert value != function(100) assert len(calls_made) == 2 def test_invalidate_with_refresh(): calls_made = [] @cache_memoize(10) def function(argument): calls_made.append(argument) return random.random() value = function(100, _refresh=False) assert value == function(100, _refresh=False) assert len(calls_made) == 1 new_value = function(100, _refresh=True) assert value != new_value assert len(calls_made) == 2 function.invalidate(999, _refresh=True) # different args assert new_value == function(100, _refresh=False) assert len(calls_made) == 2 function.invalidate(100, _refresh=0) # known args assert new_value != function(100, _refresh=False) assert len(calls_made) == 3 def test_get_cache_key(): @cache_memoize(10) def funky(argument): pass assert funky.get_cache_key(100) == "eb96668ba0d14dc7748161fb1d000239" assert funky.get_cache_key(100, _refresh=True) == "eb96668ba0d14dc7748161fb1d000239" def test_cache_memoize_custom_alias(): calls_made = [] def runmeonce(a): calls_made.append(a) return a * 2 runmeonce_default = cache_memoize(10)(runmeonce) runmeonce_locmem = cache_memoize(10, cache_alias="other")(runmeonce) runmeonce_default(10) assert len(calls_made) == 1 runmeonce_default(10) assert len(calls_made) == 1 runmeonce_locmem(10) assert len(calls_made) == 2 runmeonce_locmem(10) assert len(calls_made) == 2 def test_cache_memoize_works_with_custom_key_generator(): calls_made = [] def key_generator(*args): key = (":{}" * len(args)).format(*args) return "custom_namespace:{}".format(key) @cache_memoize(10, key_generator_callable=key_generator) def runmeonce(arg1, arg2): calls_made.append((arg1, arg2)) return arg1 + 1 runmeonce(1, 2) runmeonce(1, 2) assert len(calls_made) == 1 runmeonce(1, 3) assert len(calls_made) == 2 def test_invalidate_with_custom_key_generator(): calls_made = [] def key_generator(*args): key = (":{}" * len(args)).format(*args) return "custom_namespace:{}".format(key) @cache_memoize(10, key_generator_callable=key_generator) def runmeonce(arg1, arg2): calls_made.append((arg1, arg2)) return arg1 + 1 runmeonce(1, 2) runmeonce(1, 2) assert len(calls_made) == 1 runmeonce.invalidate(999, 10) # different args assert runmeonce(1, 2) assert len(calls_made) == 1 runmeonce.invalidate(1, 2) # known args assert runmeonce(1, 2) assert len(calls_made) == 2 def test_get_cache_key_with_custom_key_generator(): @cache_memoize(10, key_generator_callable=lambda x: x * 10) def funky(argument): pass assert funky.get_cache_key("1") == "1111111111" def test_get_cache_key_with_extra_components(): def funky(argument): pass fn1 = cache_memoize(10, extra={"version": 1})(funky) fn2 = cache_memoize(10, extra={"version": 1})(funky) fn3 = cache_memoize(10, extra={"version": 2})(funky) fn4 = cache_memoize(10, extra=lambda x: x * 2)(funky) fn5 = cache_memoize(10, extra=lambda x: x * 3)(funky) assert fn1.get_cache_key(1) == fn2.get_cache_key(1) assert fn2.get_cache_key(1) != fn3.get_cache_key(1) assert fn4.get_cache_key(1) != fn5.get_cache_key(1) def test_cache_memoize_none_value(): calls_made = [] @cache_memoize(10) def runmeonce(a): calls_made.append(a) result = runmeonce(20) assert len(calls_made) == 1 assert result is None result = runmeonce(20) assert len(calls_made) == 1 assert result is None def test_cache_memoize_thread_safety(): calls_made = [] lock = Lock() @cache_memoize(10, cache_alias="thread_local", args_rewrite=lambda *args: args[1:]) def runmeonce(_calls_made, a): # Do not include _calls_made in the key. # Because we're using threads, call_made cannot be used from the # outer scope, so we need to inject it with the arguments. with lock: return _calls_made.append(a) def func_that_calls_runmeonce(*args): runmeonce(*args) threads = [ Thread(target=func_that_calls_runmeonce, args=(calls_made, 1)) for x in range(2) ] for thread in threads: thread.start() for thread in threads: thread.join() assert len(calls_made) == 2 class TestException(Exception): pass class DerivedTestException(TestException): pass class SecondTestException(Exception): pass def test_dont_cache_exceptions(): calls_made = [] @cache_memoize(10, prefix="dont_cache_exceptions") def raise_test_exception(): calls_made.append(1) raise TestException # Caching of exceptions i turned off. These should both call the function # and propagate the exception. with pytest.raises(TestException): raise_test_exception() with pytest.raises(TestException): raise_test_exception() assert len(calls_made) == 2 def test_cache_exception(): calls_made = [] @cache_memoize(10, cache_exceptions=TestException, prefix="cache_exceptions") def raise_test_exception(): calls_made.append(1) raise TestException # The first call should be cached, raised and the second call should # re-raise the cached exception without calling the cached function. with pytest.raises(TestException): raise_test_exception() with pytest.raises(TestException): raise_test_exception() assert len(calls_made) == 1 def test_cache_exceptions(): calls_made = [] # It should be possible to specify a tuple of exceptions to cache. @cache_memoize( 10, cache_exceptions=(TestException, SecondTestException), prefix="cache_exceptions", ) def raise_test_exception(): calls_made.append(1) raise TestException with pytest.raises(TestException): raise_test_exception() with pytest.raises(TestException): raise_test_exception() assert len(calls_made) == 1 def test_cache_derived_exceptions(): calls_made = [] @cache_memoize(10, cache_exceptions=TestException, prefix="cache_exceptions") def raise_test_exception(): calls_made.append(1) raise DerivedTestException # We're raising DerivedTestException, which is a subclass of TestException # and should thus be cached. with pytest.raises(DerivedTestException): raise_test_exception() with pytest.raises(DerivedTestException): raise_test_exception() assert len(calls_made) == 1 def test_dont_cache_unrelated_exceptions(): calls_made = [] @cache_memoize(10, cache_exceptions=TestException, prefix="cache_exceptions") def raise_test_exception(): calls_made.append(1) raise SecondTestException # We're raising SecondTestException, which is not a subclass # of TestException, so the calls shouldn't be cached. with pytest.raises(SecondTestException): raise_test_exception() with pytest.raises(SecondTestException): raise_test_exception() assert len(calls_made) == 2