Caching decorator


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. from datetime import datetime, timedelta
  2. from copy import deepcopy
  3. from threading import RLock
  4.  
  5. def timed_cache(seconds=0, minutes=0, hours=0, days=0):
  6.  
  7. time_delta = timedelta( seconds=seconds,
  8. minutes=minutes,
  9. hours=hours,
  10. days=days )
  11.  
  12. def decorate(f):
  13.  
  14. f._lock = RLock()
  15. f._updates = {}
  16. f._results = {}
  17.  
  18. def do_cache(*args, **kwargs):
  19.  
  20. lock = f._lock
  21. lock.acquire()
  22.  
  23. try:
  24. key = (args, tuple(sorted(kwargs.items(), key=lambda i:i[0])))
  25.  
  26. updates = f._updates
  27. results = f._results
  28.  
  29. t = datetime.now()
  30. updated = updates.get(key, t)
  31.  
  32. if key not in results or t-updated > time_delta:
  33. # Calculate
  34. updates[key] = t
  35. result = f(*args, **kwargs)
  36. results[key] = deepcopy(result)
  37. return result
  38.  
  39. else:
  40. # Cache
  41. return deepcopy(results[key])
  42.  
  43. finally:
  44. lock.release()
  45.  
  46. return do_cache
  47.  
  48. return decorate

URL: http://www.willmcgugan.com/blog/tech/2007/10/14/timed-caching-decorator/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.