src/pyams_utils/wsgi.py
changeset 1 3f89629b9e54
child 72 9049384a2bd4
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/wsgi.py	Thu Feb 19 00:46:48 2015 +0100
@@ -0,0 +1,42 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+# import standard library
+
+# import interfaces
+
+# import packages
+
+
+def wsgi_environ_cache(*names):
+    """Wrap a function/method to cache its result for call into request.environ
+
+    :param list[string] names: keys to cache into environ, the len(names) must
+    be equal to the result's length or scalar
+    :return:
+    """
+    def decorator(fn):
+        def function_wrapper(self, request):
+            scalar = len(names) == 1
+            try:
+                rs = [request.environ[cached_key] for cached_key in names]
+            except KeyError:
+                rs = fn(self, request)
+                if scalar:
+                    rs = [rs, ]
+                request.environ.update(zip(names, rs))
+            return rs[0] if scalar else rs
+        return function_wrapper
+
+    return decorator