Skip to content

Instantly share code, notes, and snippets.

@beaumartinez
Created August 9, 2011 21:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beaumartinez/1135223 to your computer and use it in GitHub Desktop.
Save beaumartinez/1135223 to your computer and use it in GitHub Desktop.
Use GAE's Memcache to cache functions
import google.appengine.api.memcache
DEFAULT_CACHE_TTL = 60 * 60 * 24
def cache(function, ttl=DEFAULT_CACHE_TTL):
'''Cache `function` and its arguments for `ttl` seconds in GAE's
Memcache.
Usable as a decorator.
'''
def cache_function(*arguments, **keyword_arguments):
function_name = '{}.{}'.format(function.__module__, function.__name__)
signature = (function_name, arguments, keyword_arguments)
signature = str(signature)
value = google.appengine.api.memcache.get(signature)
if value is None:
value = function(*arguments, **keyword_arguments)
google.appengine.api.memcache.add(signature, value, time=ttl)
return value
return cache_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment