Thursday, July 24, 2008

Google App Engine memcache wrapper

According to Google's App Engine documentation, Memcache is a "high-performance, distributed memory object caching system, intended for use in speeding up dynamic web applications by alleviating load on the datastore." In this post I show a method to decrease code duplication when fetching multiple kinds of entity using Memcache.

This function forms the core of the scheme I use.


def fetch_entity(memcache_key, fetch_from_db):
entity=memcache.get(memcache_key)
if entity is None:
entity=fetch_from_db()
memcache.add(memcache_key, entity, 60)
return entity


First Memcache is checked for a cached entity with the given key. If no entity is found in the cache, then the entity is fetched from the database using the "fetch_from_db" method passed in as a parameter. The enity is cached using the key and is returned by the function.

I use this function for fetching all the entities for my Google App Engine app at etapic.name.

No comments: