Posted By

manatlan on 09/09/09


Tagged

python cache Decorator


Versions (?)

cache decorator


 / Published in: Python
 

  1. import cPickle,hashlib,tempfile,os,time,types
  2.  
  3. def cache(nbsec=0,path=None,islog=False):
  4. """ cache (decorator) tout retour de methode en pickable
  5. - nbsec : (opt) nb secondes du cache (si =0 unlimited)
  6. - path : (opt) chemin pour stocker le pickle (sinon temp dir)
  7. - islog: (opt) affiche un log clair des manips
  8. """
  9. def _f2(*args,**kwargs):
  10. mname = _f2.fct.__name__
  11. def log(msg): print "*** CACHE %s (%ds): " % (mname,nbsec),msg
  12. file=os.path.join(path or tempfile.gettempdir(),
  13. "zcache_%s_%s.pickle" % (mname,hashlib.md5(str(args)+str(kwargs)).hexdigest())
  14. )
  15. if os.path.isfile(file):
  16. if nbsec>0:
  17. ftime = os.stat(file).st_mtime
  18. ntime = time.time()
  19. isLoad = ftime + nbsec > ntime
  20. if isLoad:
  21. if islog: log("use cache : %s renew in %ds" % (file,nbsec - (ntime - ftime)) )
  22. else:
  23. if islog: log("cache has expired since %d sec" % (ntime - ftime))
  24. else:
  25. isLoad = True
  26. if islog: log("use cache : %s (no expiration time)" % (file,) )
  27. if isLoad:
  28. return cPickle.load(open(file,"rb"))
  29. else:
  30. if islog: log("no cache file")
  31.  
  32. val = _f2.fct(*args, **kwargs)
  33. if islog: log("create %s"%file)
  34. fid=open(file,"wb")
  35. cPickle.dump(val,fid)
  36. fid.close()
  37. return val
  38.  
  39. if type(nbsec) == types.FunctionType: # to be able to work without decorator params
  40. _f2.fct, nbsec= nbsec , 0
  41. return _f2
  42. else:
  43. def _f1(func):
  44. _f2.fct = func
  45. return _f2
  46. return _f1

Report this snippet  

You need to login to post a comment.