Thursday, January 21, 2010

Using Google App Engine memcache

I finally got memcache working correctly with my Google App Engine Model.  I have read where this version of memcache is a bit different than you would expect.  It works just like memcached, but specific to GAE and perhaps a different backend implementation.  Either way, it keeps with memcached APIs and is very easy to use.  I wanted to play with this and see how it works on my test app, the run tracker.  My app's data model is a runner who has entered many runs.  I figured a good use of a cache was to cache the list of runs a runner has entered.

A "Run" is an app engine Model class.  My initial thought was to add that to memcache using this call:

memcache.set(users.get_current_user().email(), runs)

Turns out I made a rookie mistake here.  What I intended to do was add the set of "runs" to the cache with the users email address as the key.  The problem is that it never worked.  I kept getting errors on the template rendering telling me that "'Runs' object is not iterable".  My assumption is that Runs is not a dataset anymore.  Turns out I was correct.  I found this blog post that pointed out my mistake.  I was caching the query and not the data itself.  I had to get the data first

runs = Runs.all().ancestor(runner)

Now this worked, memcache is working on my app!  To get my set of runs from the cache, all I had to do is this:

runs = memcache.get(users.get_current_user().email())

Very easy, no problems after that one speed bump.  I did see something interesting in that blog post I posted above though.  A link at the end of it pointed to this blog.  This is an excellent article on making your memcache more efficient.  I implemented the serialize/deserialize code in my app.  Not sure how much my app will benefit, but it was nice to put in there.

That is it, I need to clean up some code and will post new versions soon.

No comments:

Post a Comment