#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)
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