]> git.llucax.com Git - software/blitiri.git/commitdiff
Make the cached() decorator take into account all arguments
authorAlberto Bertogli <albertito@blitiri.com.ar>
Mon, 1 Sep 2008 19:42:06 +0000 (16:42 -0300)
committerAlberto Bertogli <albertito@blitiri.com.ar>
Sat, 6 Sep 2008 13:54:21 +0000 (10:54 -0300)
Also, while at it, move the test for cache_path into the decorator, and
fix the cache file name.

Signed-off-by: Alberto Bertogli <albertito@blitiri.com.ar>
blitiri.cgi

index df2920544f83b64c018ad6e39699780b91c43189..347d27a86eebcbd933a1e4cde226cf967be55a93 100755 (executable)
@@ -410,22 +410,30 @@ div.section h1 {
 
 """
 
+
 # Cache decorator
+# It only works if the function is pure (that is, its return value depends
+# only on its arguments), and if all the arguments are hash()eable.
 def cached(f):
-       def decorate(obj, *args, **kwargs):
-               if cache_path is None: # cache disabled
-                       s = f(obj, *args, **kwargs)
-               else:
-                       cache_file = os.path.join(cache_path,
-                                       'blitiri.cache.%s.html' % hash(obj))
-                       try:
-                               s = open(cache_file).read()
-                       except:
-                               s = f(obj, *args, **kwargs)
-                               open(cache_file, 'w').write(s)
+       # do not decorate if the cache is disabled
+       if cache_path is None:
+               return f
+
+       def decorate(*args, **kwargs):
+               hashes = '-'.join( str(hash(x)) for x in args +
+                               tuple(kwargs.items()) )
+               fname = 'blitiri.%s.%s.cache' % (f.__name__, hashes)
+               cache_file = os.path.join(cache_path, fname)
+               try:
+                       s = open(cache_file).read()
+               except:
+                       s = f(*args, **kwargs)
+                       open(cache_file, 'w').write(s)
                return s
+
        return decorate
 
+
 # helper functions
 def rst_to_html(rst, secure = True):
        settings = {