src/pyams_utils/container.py
changeset 36 7398e25bad99
child 56 01de65ad00fb
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/container.py	Wed Jun 17 10:01:29 2015 +0200
@@ -0,0 +1,54 @@
+#
+# 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 zope.container.interfaces import IContainer, IContained
+from zope.location.interfaces import ISublocations
+
+# import packages
+from BTrees.OOBTree import OOBTree
+from persistent.list import PersistentList
+from pyams_utils.adapter import adapter_config, ContextAdapter
+from pyramid.threadlocal import get_current_registry
+from zope.container.ordered import OrderedContainer
+
+
+class BTreeOrderedContainer(OrderedContainer):
+    """BTree based ordered container"""
+
+    def __init__(self):
+        self._data = OOBTree()
+        self._order = PersistentList()
+
+
+@adapter_config(context=IContained, provides=ISublocations)
+class ContainerSublocationsAdapter(ContextAdapter):
+    """Container sub-locations adapter"""
+
+    def sublocations(self):
+        context = self.context
+        # Check for adapted sub-locations first...
+        registry = get_current_registry()
+        for name, adapter in registry.getAdapters((context,), ISublocations):
+            if not name:  # don't reuse default adapter!!
+                continue
+            for location in adapter.sublocations():
+                yield location
+        # then yield container items
+        if IContainer.providedBy(context):
+            for key in context:
+                yield context[key]