Skip to content

Instantly share code, notes, and snippets.

@abahgat
Last active January 22, 2021 00:43
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save abahgat/1395810 to your computer and use it in GitHub Desktop.
Save abahgat/1395810 to your computer and use it in GitHub Desktop.
A Python decorator to cache method results using memcache on Google AppEngine
import functools
import logging
from google.appengine.api import memcache
def cached(time=1200):
"""
Decorator that caches the result of a method for the specified time in seconds.
Use it as:
@cached(time=1200)
def functionToCache(arguments):
...
"""
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
key = '%s%s%s' % (function.__name__, str(args), str(kwargs))
value = memcache.get(key)
logging.debug('Cache lookup for %s, found? %s', key, value != None)
if not value:
value = function(*args, **kwargs)
memcache.set(key, value, time=time)
return value
return wrapper
return decorator
@glmvrml
Copy link

glmvrml commented Sep 9, 2014

what if value is None or 0?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment