Added custom region name for views cache
authorThierry Florac <thierry.florac@onf.fr>
Tue, 27 Jun 2017 15:10:36 +0200
changeset 95 83d6b58ada5f
parent 94 db2826d440df
child 96 120f7842a8cb
Added custom region name for views cache
src/pyams_content/shared/view/__init__.py
--- a/src/pyams_content/shared/view/__init__.py	Tue Jun 27 11:57:56 2017 +0200
+++ b/src/pyams_content/shared/view/__init__.py	Tue Jun 27 15:10:36 2017 +0200
@@ -22,6 +22,7 @@
 from pyams_content.shared.view.interfaces import IView, IWfView, IViewQuery, IViewQueryParamsExtension, \
     IViewQueryFilterExtension, VIEW_CONTENT_TYPE, VIEW_CONTENT_NAME
 from zope.intid.interfaces import IIntIds
+from zope.lifecycleevent.interfaces import IObjectModifiedEvent
 
 # import packages
 from hypatia.catalog import CatalogQuery
@@ -33,11 +34,13 @@
 from pyams_utils.list import unique
 from pyams_utils.registry import get_utility
 from pyams_workflow.interfaces import IWorkflow
+from pyramid.events import subscriber
 from pyramid.threadlocal import get_current_registry
 from zope.interface import implementer
 from zope.schema.fieldproperty import FieldProperty
 
 
+VIEWS_CACHE_REGION = 'views'
 VIEWS_CACHE_NAME = 'PyAMS::view'
 VIEWS_CACHE_KEY = 'view_{view}.context_{context}'
 
@@ -55,7 +58,7 @@
 
     def get_results(self, context, limit=None):
         intids = get_utility(IIntIds)
-        views_cache = get_cache('default', VIEWS_CACHE_NAME)
+        views_cache = get_cache(VIEWS_CACHE_REGION, VIEWS_CACHE_NAME)
         cache_key = VIEWS_CACHE_KEY.format(view=intids.queryId(self),
                                            context=intids.queryId(context))
         try:
@@ -116,3 +119,10 @@
                                     key=lambda x: x[1].weight):
             items = adapter.filter(context, items)
         return unique(items)
+
+
+@subscriber(IObjectModifiedEvent, context_selector=IWfView)
+def handle_modified_view(view):
+    """Invalidate views cache when a view is modified"""
+    views_cache = get_cache(VIEWS_CACHE_REGION, VIEWS_CACHE_NAME)
+    views_cache.clear()