Skip to content

Instantly share code, notes, and snippets.

@mohi7solanki
Created October 11, 2018 07:14
Show Gist options
  • Save mohi7solanki/dc99385896a6ee7e9e4c8be2e2a2beba to your computer and use it in GitHub Desktop.
Save mohi7solanki/dc99385896a6ee7e9e4c8be2e2a2beba to your computer and use it in GitHub Desktop.
import hashlib
import os
import pickle
CACHE_DIR = '~/.playlist_length'
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR)
class CacheUtil:
def __init__(self, path):
self.dir_path = os.path.abspath(path)
self.cache = self._get_cached_data()
@staticmethod
def get_hash(string):
return hashlib.md5(string.encode('utf-8')).hexdigest()
def _get_cached_data(self):
file_name = self.get_hash(self.dir_path)
cache_file_path = os.path.join(CACHE_DIR, file_name)
if not os.path.exists(cache_file_path):
with open(os.path.join(CACHE_DIR, file_name), 'wb'):
data = {}
else:
with open(cache_file_path, 'rb') as file:
data = pickle.load(file)
return data
def __call__(self, func):
def wrap(file_path):
file_hash = self.get_hash(file_path)
if not file_hash in self.cache:
result = func(file_path)
self.cache[file_hash] = result
return self.cache[file_hash]
return wrap
def save(self):
cache_file_path = os.path.join(CACHE_DIR, file_name)
with open(cache_file_path, 'wb') as file:
pickle.dump(self.cache, file, protocol=pickle.HIGHEST_PROTOCOL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment