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 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 class to implement a cache.

from 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):['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):['event'].data['index']['event'].data['set']
print 'Checking if %s is cached.'%index
except IndexError:
print 'Not cached. Need to retrieve from DB.'

if __name__=="__main__":
subscribe(EventSetPush, HandleMySetPush)
subscribe(EventSetGet, HandleMySetGet)
set_obj.push('Hello World!')
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.

No comments :

Post a Comment