Wednesday, January 7, 2009

Implementing a cache with the boduch Python library

I'm going to show a simple example of how to use the boduch.data.Set class to implement a caching. The Set class is nothing but a Python list that emits events. All we need to do is subscribe to the appropriate Set events.
#Using the boduch.data.Set class to implement a cache.

from boduch.data import Set
from boduch.event import subscribe, EventSetPush, EventSetGet
from boduch.handle import Handle

class HandleMySetPush(Handle):
def __init__(self, *args, **kw):
Handle.__init__(self, *args, **kw)

def run(self):
new_obj=self.data['event'].data['obj']
print 'Cache updated. Now updating DB with %s'%new_obj

class HandleMySetGet(Handle):
def __init__(self, *args, **kw):
Handle.__init__(self, *args, **kw)

def run(self):
index=self.data['event'].data['index']
set_obj=self.data['event'].data['set']
print 'Checking if %s is cached.'%index
try:
set_obj.data[index]
except IndexError:
print 'Not cached. Need to retrieve from DB.'

if __name__=="__main__":
subscribe(EventSetPush, HandleMySetPush)
subscribe(EventSetGet, HandleMySetGet)
set_obj=Set()
set_obj.push('Hello World!')
set_obj.get(0)
Here, we have created two event handles for our Set instance; HandleMySetPush and HandleMySetGet. Both event handles are invoked for the Set.push() and the Set.get() methods respectively.

In the main program, we create our Set instance and subscribe our new handles to two Set events.

The first handle, HandleMySetPush, is invoked after the actual Set instance is updated. This means that once the cache has been updated, we now have an opportunity to update a database with this new value. Updating the database is simply an example use of this handler. You could perform whatever action needed.

The second handle, HandleMySetGet, is invoked before the the actual Set instance is updated. This means that the handler can check if the requested object is cached. If not, it now has an opportunity to update the cache before the invokee can complain about a non-existent element.