Skip to content

Instantly share code, notes, and snippets.

@radomd92
Created September 10, 2020 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radomd92/09e80ada64dd0072f96907e97ab0d421 to your computer and use it in GitHub Desktop.
Save radomd92/09e80ada64dd0072f96907e97ab0d421 to your computer and use it in GitHub Desktop.
simple KVS cache using dictionary. Adaptable for redis
from uuid import uuid4
class MyRedisAPI(object):
def __init__(self):
self.kvstore = {}
def set_identifier(self, class_):
self.identifier = class_.__name__ + str(uuid4())
def cache_value(self, value):
def cache_value_wrapper(f):
def wrapper(*args, **kwargs):
key = str(self.identifier) + str(value) + '_'.join([str(s) for s in args])
if key not in self.kvstore:
v = f(*args, **kwargs)
self.kvstore[key] = v
print('funccall', key, self.kvstore[key])
return v
else:
print('kvstore', key, self.kvstore[key])
return self.kvstore[key]
return wrapper
return cache_value_wrapper
class C(object):
redis_api = MyRedisAPI()
def __init__(self):
self.redis_api.set_identifier(self.__class__)
@redis_api.cache_value('v')
def f(self, s):
return 'alskdalkjr' + s
if __name__ == '__main__':
c = C()
print(c.f('toto'))
print(c.f('toto'))
print(c.f('tasdlk'))
print(c.f('totsadlki'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment