src/pyams_utils/cache.py
changeset 289 c8e21d7dd685
child 292 b338586588ad
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/cache.py	Wed Dec 05 12:45:56 2018 +0100
@@ -0,0 +1,56 @@
+#
+# 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
+from persistent.interfaces import IPersistent
+from pyams_utils.interfaces import ICacheKeyValue
+from pyams_utils.interfaces.tales import ITALESExtension
+
+# import packages
+from pyams_utils.adapter import adapter_config, ContextRequestViewAdapter
+from zope.interface import Interface
+
+
+@adapter_config(context=object, provides=ICacheKeyValue)
+def object_cache_key_adapter(obj):
+    return str(id(obj))
+
+
+@adapter_config(context=str, provides=ICacheKeyValue)
+def string_cache_key_adapter(obj):
+    return obj
+
+
+@adapter_config(context=IPersistent, provides=ICacheKeyValue)
+def persistent_cache_key_adapter(obj):
+    if obj._p_oid:
+        return str(int.from_bytes(obj._p_oid, byteorder='big'))
+    else:  # unsaved object
+        return str(id(obj))
+
+
+@adapter_config(name='cache_key', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class CacheKeyTalesExtension(ContextRequestViewAdapter):
+    """extension:cache_key(context) TALES extension
+
+    A PyAMS TALES extension which allows to render cache key value for a given context.
+    """
+
+    def render(self, context=None):
+        if context is None:
+            context = self.request.context
+        return ICacheKeyValue(context)