Updated request_property decorator
authorThierry Florac <thierry.florac@onf.fr>
Thu, 29 Mar 2018 10:43:33 +0200
changeset 160 db952e3e1583
parent 159 6576e28d6f5d
child 161 2e3f8f762158
Updated request_property decorator
src/pyams_utils/request.py
--- a/src/pyams_utils/request.py	Thu Mar 29 10:42:41 2018 +0200
+++ b/src/pyams_utils/request.py	Thu Mar 29 10:43:33 2018 +0200
@@ -14,6 +14,8 @@
 
 
 # import standard library
+import logging
+logger = logging.getLogger('PyAMS (utils)')
 
 # import interfaces
 from pyams_utils.interfaces import MissingRequestError, ICacheKeyValue
@@ -81,21 +83,34 @@
     def request_decorator(func):
 
         def wrapper(obj, key, *args, **kwargs):
-            request = check_request()
-            if callable(key):
-                key = key(obj, *args, **kwargs)
-            if not key:
-                key = '{0}::{1}'.format(prefix or func.__name__, ICacheKeyValue(obj))
-                if args:
-                    key += '::' + '::'.join((ICacheKeyValue(arg) for arg in args))
-                if kwargs:
-                    key += '::' + '::'.join((ICacheKeyValue(arg) for arg in kwargs.items()))
-            data = get_request_data(request, key, _marker)
-            if data is _marker:
+            request = query_request()
+            if request is not None:
+                if callable(key):
+                    key = key(obj, *args, **kwargs)
+                if not key:
+                    key = prefix or func.__name__
+                    if obj is not request:
+                        key += '::{0}'.format(ICacheKeyValue(obj))
+                    key_args = tuple(filter(lambda x: x is not request, args))
+                    if key_args:
+                        key += '::' + '::'.join((ICacheKeyValue(arg) for arg in key_args))
+                    if kwargs:
+                        key += '::' + \
+                               '::'.join(('{0}={1}'.format(key, ICacheKeyValue(val)) for key, val in kwargs.items()))
+                logger.debug(">>> Looking for request cache key {0}".format(key))
+                data = get_request_data(request, key, _marker)
+                if data is _marker:
+                    logger.debug("<<< no cached value!")
+                    data = func
+                    if callable(data):
+                        data = data(obj, *args, **kwargs)
+                    set_request_data(request, key, data)
+                else:
+                    logger.debug("<<< cached value found!")
+            else:
                 data = func
                 if callable(data):
                     data = data(obj, *args, **kwargs)
-                set_request_data(request, key, data)
             return data
 
         return lambda x, *args, **kwargs: wrapper(x, key, *args, **kwargs)