Last active
February 29, 2016 11:20
-
-
Save raztud/bcb9e43534ec2e06c030 to your computer and use it in GitHub Desktop.
memcached decorator for functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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