Antoine Bertin avatar Antoine Bertin committed 8d6a5a5

Add a cache_for method

Comments (0)

Files changed (2)

dogpile/cache/region.py

 
             generate_something.invalidate(5, 6)
 
+        Another attribute ``cache_for`` is added to provide extra caching
+        possibilities within the function. This is a convenience method for
+        :meth:`.CacheRegion.set` with the same key generator as it would
+        have been by using ``cache_on_arguments``. Pass to ``cache_for()``
+        the same arguments you'd pass to the function itself and an extra
+        keyword argument ``cache_value`` that contains the value to cache::
+
+            generate_something.cache_for(5, 6, cache_value=3)
+
         The default key generation will use the name
         of the function, the module name for the function,
         the arguments passed, as well as an optional "namespace"
                 key = key_generator(*arg, **kw)
                 self.delete(key)
 
+            def cache_for(*arg, **kw):
+                value = kw.pop('cache_value')
+                key = key_generator(*arg, **kw)
+                self.set(key, value)
+
+            decorate.cache_for = cache_for
             decorate.invalidate = invalidate
 
             return decorate

tests/cache/test_decorator.py

         go.invalidate(1, 2)
         eq_(go(1, 2), (3, 1, 2))
 
+    def test_explicit_set(self):
+        go = self._fixture(expiration_time=1)
+        eq_(go(1, 2), (1, 1, 2))
+        go.cache_for(1, 2, cache_value=(5, 1, 2))
+        eq_(go(3, 4), (2, 3, 4))
+        eq_(go(1, 2), (5, 1, 2))
+        go.invalidate(1, 2)
+        eq_(go(1, 2), (3, 1, 2))
+        go.cache_for(1, 3, cache_value=(0, 1, 3))
+        eq_(go(1, 3), (0, 1, 3))
+
 class KeyGenerationTest(TestCase):
     def _keygen_decorator(self, namespace=None):
         canary = []
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.