sarcachem.py

  1. import memcache, time
  2.  
  3. HOST = "127.0.0.1"
  4. PORT = "11211"
  5. MC_CLIENT = memcache.Client(['%s:%s'%(HOST,PORT)], debug=0)
  6.  
  7. class sarcachem:
  8.  
  9. class helper:
  10.  
  11. def __init__(self, outer, fun):
  12. self.outer = outer
  13. self.fun = fun
  14.  
  15. def __call__(self, *args, **kwargs):
  16. # If cached value does not exist
  17. # 1. Check to see if it is locked
  18. # If it is, wait until it unlocks
  19. # If it is not, lock and calculate value,
  20. # unlock when finished
  21. # Return cached value
  22. key = "%s.%s->(%s,%s)"%(self.outer.salt,
  23. self.fun.func_name,
  24. repr(args),
  25. repr(kwargs))
  26. key_lock = "00_locked_%s"%(key)
  27.  
  28. if MC_CLIENT.get(key) is None:
  29. if not MC_CLIENT.get(key_lock):
  30. MC_CLIENT.set(key_lock,True)
  31. result = self.fun(*args, **kwargs)
  32. MC_CLIENT.set(key,result,time=self.outer.time)
  33. print "Storing: ", key, ": ", MC_CLIENT.get(key)
  34. MC_CLIENT.delete(key_lock)
  35. else:
  36. while True:
  37. time.sleep(1)
  38. if not MC_CLIENT.get(key_lock):
  39. break
  40. else:
  41. continue
  42.  
  43. return MC_CLIENT.get(key)
  44.  
  45. def __init__(self,time=3,salt="base"):
  46. """ In this function we set all our decorator's parameters """
  47. self.time = time
  48. self.salt = salt
  49.  
  50. def __call__(self, fun):
  51. return sarcachem.helper(self, fun)

And here is the way you can use it:

  1. from sarcachem import sarcachem
  2.  
  3. @sarcachem(10,__file__)
  4. def fib(number=0):
  5.  
  6. # Suck my life into the CPUHOLE
  7. for i in range(0,100000):
  8. i+100;
  9. # END OF LIFE SUCKER
  10.  
  11. if number==0:
  12. return 0
  13. elif number==1:
  14. return 1
  15. else:
  16. return int(fib(number-1)) + int(fib(number-2))
  17.  
  18. if __name__=="__main__":
  19. print fib(100), fib(29)
Tagged with:  
Share →
This site is protected by Comment SPAM Wiper.