How To Associate Objects to a Cache Manager Programmatically

Zope offers a caching framework with some cache managers available "out
of the box". Your friendly Zope documentation tells you how to add a
cache manager in the ZMI and associate objects with it. Since my site
setup for our application is done from python code, I want this
automated. All I needed was a tiny bit of digging around in the Zope
source code and here we go...

First step: Add a cache manager object.
Depending on what we need (HTTP Cache Manager or RAM Cache Manager), our
"add" method is a bit different. In this example we are going to use a
HTTP Cache Manager to set the caching headers on uploaded images.
Here is what we use ('assets' is the object where we add our stuff):

cache_manager_id = 'HTTPCacheManager'
if cache_manager_id not in assets.objectIds():
assets.manage_addProduct['StandardCacheManagers'].manage_addAcceleratedHTTPCacheManager(\
cache_manager_id)

We throw the id of our cache manager into a variable, then check for its
existence. If it's not around, we add it. Easy enough. Next step is to
configure it:

The "settings" dictionary is the same stuff that you can edit in the
"Properties" tab of the cachemanager in the ZMI. Then we use the
manage_editProps method to set this stuff (along with the title). After
this we simply want to add all objects in this folder to be associated
with this cache manager:

for ob in assets.objectValues():
if getattr(ob.aq_explicit, '_isCacheable', 0) \
and ob.getId() not in ['assets', cache_manager_id]:
ob.ZCacheable_setManagerId(cache_manager_id)

This code gets all the objects in our folder (if you need another set of
objects, this is obviously the place to change that). It then iterates
over them and tests if the object can be cached and is not the cache
manager itself. Then it sets the association with the cache on each
object. And with that we're done.

Life in Athens (Greece) for a foreigner from the other side of the mountains.
And with an interest in digital life and the feeling of change in a big city.
Multilingual English - German - Greek.Main blog page