Updated request_property decorator ZTK-1.1
authorThierry Florac <thierry.florac@onf.fr>
Tue, 17 Nov 2015 12:10:57 +0100
branchZTK-1.1
changeset 270 edb444bb5408
parent 269 0b0004edfba6
child 271 facd1203256f
Updated request_property decorator
src/ztfy/utils/property.py
--- a/src/ztfy/utils/property.py	Thu Oct 22 14:03:31 2015 +0200
+++ b/src/ztfy/utils/property.py	Tue Nov 17 12:10:57 2015 +0100
@@ -69,24 +69,29 @@
 
 _marker = object()
 
-class request_property(object):
-    """Define a request cached property"""
+def request_property(key):
+    """Define a method decorator used to store result into request's annotations
 
-    def __init__(self, fget, key=None):
-        self.fget = fget
-        if key is None:
-            key = "%s.%s" % (fget.__module__, fget.__name__)
-        self.key = key
+    `key` is a required argument; if None, the key will be the method's object
+    """
 
-    def __get__(self, obj, cls):
-        if obj is None:
-            return self
-        request = queryRequest()
-        data = getRequestData(self.key, request, _marker)
-        if data is _marker:
-            data = self.fget(obj)
-            setRequestData(self.key, data, request)
-        return data
+    def request_decorator(func):
+        def wrapper(obj, key, *args, **kwargs):
+            request = queryRequest()
+            if callable(key):
+                key = key(obj)
+            if not key:
+                key = '{0!r}'.format(obj)
+            data = getRequestData(key, request, _marker)
+            if data is _marker:
+                data = func
+                if callable(data):
+                    data = data(obj, *args, **kwargs)
+                setRequestData(key, data, request)
+            return data
+        return lambda x: wrapper(x, key=key)
+
+    return request_decorator
 
 
 class session_property(object):