import json import os from datetime import datetime from config import CACHE_DIR DEFAULT_CACHE_DIR = CACHE_DIR DEFAULT_CACHE_TIME = float('inf') class file_cache(object): def __init__(self, cache_dir=None, cache_time=None): self.cache_dir = cache_dir or DEFAULT_CACHE_DIR self.cache_time = cache_time or DEFAULT_CACHE_TIME def get_cache_file(self, f): my_name = __name__ f_name = f.__name__ return os.path.join(self.cache_dir, "{}.{}".format(my_name, f_name)) def get_cache(self, f, args, kwargs): cache_file = self.get_cache_file(f) if os.path.exists(cache_file): with open(cache_file, 'r') as cf: cache_entries = json.load(cf) for cache_entry in cache_entries: if cache_entry.get('args') == list(args) and cache_entry.get('kwargs') == kwargs: return cache_entry.get('rv') return None def set_cache(self, f, args, kwargs, rv): cache_file = self.get_cache_file(f) cache_entries = [] if os.path.exists(cache_file): with open(cache_file, 'r') as cf: cache_entries = json.load(cf) for idx, cache_entry in enumerate(cache_entries): if cache_entry.get('args') == list(args) and cache_entry.get('kwargs') == kwargs: cache_entry['rv'] = rv cache_entries[idx] = cache_entry break else: cache_entry = { 'args': list(args), 'kwargs': kwargs, 'rv': rv, } cache_entries.append(cache_entry) with open(cache_file, 'w') as cf: json.dump(cache_entries, cf) def __call__(self, f): def wrapped_f(*args, **kwargs): cached_rv = self.get_cache(f, args, kwargs) if cached_rv: return cached_rv rv = f(*args, **kwargs) self.set_cache(f, args, kwargs, rv) return rv return wrapped_f @file_cache() def main(query): return query + str(datetime.utcnow()) if __name__ == "__main__": print(main("helo"))