Skip to content

Instantly share code, notes, and snippets.

@raztud
Last active February 29, 2016 11:20
Show Gist options
  • Save raztud/bcb9e43534ec2e06c030 to your computer and use it in GitHub Desktop.
Save raztud/bcb9e43534ec2e06c030 to your computer and use it in GitHub Desktop.
memcached decorator for functions
import time
import re
import urllib2
from memcache import Client
servers = ["127.0.0.1:11211"]
mc = Client(servers, debug=False)
def memcached_value(func):
def strigify(str):
# remove white space, {}, () and '
return re.sub('[(),{}\'\s]', '', str)
def check_cache(cache_key, auto_save=True):
'''
Returns a tuple formed by a boolean value if the value was found in cache or not and the cache value.
If the cache key was not found the cached value will be None. If the key was found, the second
element of the tuple will be the cached value.
>> check_cache('mykey')
>> (True, 5)
>> check_cache('mykey2')
>> (False, None)
'''
cache = mc.get(cache_key)
return (cache is not None, cache)
def cache_value(key, value):
mc.set(key, value)
def wrapper(*args, **kwargs):
cache_key = strigify("{0}{1}{2}".format(func.__name__, args, kwargs))
is_cached, ret_val = check_cache(cache_key)
if not is_cached:
ret_val = func(*args, **kwargs)
cache_value(cache_key, ret_val)
return ret_val
return ret_val
return wrapper
@memcached_value
def get_page(url):
response = urllib2.urlopen(url)
html = response.read()
return html
if __name__ == "__main__":
res = get_page('https://en.wikipedia.org/wiki/Main_Page')
print res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment