You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.4 KiB

  1. import pickle
  2. import os
  3. import lzma
  4. cache_path = os.path.abspath(os.path.join(__file__, "..", "__pycache__"))
  5. if not os.path.exists(cache_path):
  6. os.mkdir(cache_path)
  7. def make_key(*args, **kwargs):
  8. return args, tuple(sorted(
  9. kwargs.items(), key=lambda item: item[0]))
  10. class disk_cache:
  11. """Decorator to make persistent cache"""
  12. caches = []
  13. def __init__(self, func):
  14. self.fname = "{}.{}.dc".format(func.__module__, func.__name__)
  15. self.fname = os.path.join(cache_path, self.fname)
  16. self.func = func
  17. self.load_cache()
  18. disk_cache.caches.append(self)
  19. def __call__(self, *args, **kwargs):
  20. key = make_key(*args, **kwargs)
  21. try:
  22. res = self.cache[key]
  23. return res
  24. except KeyError:
  25. self.fresh = True
  26. res = self.func(*args, **kwargs)
  27. self.cache[key] = res
  28. return res
  29. def load_cache(self):
  30. try:
  31. with lzma.open(self.fname, 'rb') as file:
  32. cache = pickle.load(file)
  33. self.fresh = False
  34. except FileNotFoundError:
  35. cache = {}
  36. self.fresh = True
  37. self.cache = cache
  38. def save_cache(self):
  39. with lzma.open(self.fname, 'wb') as file:
  40. pickle.dump(self.cache, file, pickle.HIGHEST_PROTOCOL)
  41. def delete_cache(self):
  42. os.remove(self.fname)
  43. self.cache = {}
  44. self.fresh = True