5 changed files with 123 additions and 65 deletions
-
14ctabus.py
-
38disk_cache.py
-
35main.py
-
98print2d.py
-
1requirements.txt
@ -1,34 +1,54 @@ |
|||||
import pickle |
import pickle |
||||
import os |
import os |
||||
import lmza |
|
||||
|
import lzma |
||||
cache_path = os.path.abspath(os.path.join(__file__, "..", "__pycache__")) |
cache_path = os.path.abspath(os.path.join(__file__, "..", "__pycache__")) |
||||
if not os.path.exists(cache_path): |
if not os.path.exists(cache_path): |
||||
os.mkdir(cache_path) |
os.mkdir(cache_path) |
||||
|
|
||||
|
|
||||
|
def make_key(*args, **kwargs): |
||||
|
|
||||
|
return args, tuple(sorted( |
||||
|
kwargs.items(), key=lambda item: item[0])) |
||||
|
|
||||
|
|
||||
class disk_cache: |
class disk_cache: |
||||
|
"""Decorator to make persistent cache""" |
||||
|
caches = [] |
||||
|
|
||||
def __init__(self, func): |
def __init__(self, func): |
||||
self.fname = "{}.{}.dc".format(func.__module__, func.__name__) |
self.fname = "{}.{}.dc".format(func.__module__, func.__name__) |
||||
fname = os.path.join(cache_path, fname) |
|
||||
|
self.fname = os.path.join(cache_path, self.fname) |
||||
self.func = func |
self.func = func |
||||
self.cache = self.load_cache() |
|
||||
|
self.load_cache() |
||||
|
disk_cache.caches.append(self) |
||||
|
|
||||
def call(self, *args, **kwargs): |
|
||||
key = args + tuple(sorted(self.kwargs.items(), key=lambda item)) |
|
||||
|
def __call__(self, *args, **kwargs): |
||||
|
key = make_key(*args, **kwargs) |
||||
try: |
try: |
||||
return self.cache[key] |
|
||||
|
res = self.cache[key] |
||||
|
return res |
||||
except KeyError: |
except KeyError: |
||||
|
self.fresh = True |
||||
res = self.func(*args, **kwargs) |
res = self.func(*args, **kwargs) |
||||
self.cache[key] = res |
self.cache[key] = res |
||||
|
return res |
||||
|
|
||||
def load_cache(self): |
def load_cache(self): |
||||
try: |
try: |
||||
with lmza.open(self.fname, 'rb') as file: |
|
||||
|
with lzma.open(self.fname, 'rb') as file: |
||||
cache = pickle.load(file) |
cache = pickle.load(file) |
||||
|
self.fresh = False |
||||
except FileNotFoundError: |
except FileNotFoundError: |
||||
cache = {} |
cache = {} |
||||
|
self.fresh = True |
||||
self.cache = cache |
self.cache = cache |
||||
|
|
||||
def save_cache(self): |
def save_cache(self): |
||||
with lmza.open(self.fname, 'wb') as file: |
|
||||
pickle.dump(self.cache, file) |
|
||||
|
with lzma.open(self.fname, 'wb') as file: |
||||
|
pickle.dump(self.cache, file, pickle.HIGHEST_PROTOCOL) |
||||
|
|
||||
|
def delete_cache(self): |
||||
|
os.remove(self.fname) |
||||
|
self.cache = {} |
||||
|
self.fresh = True |
||||
@ -1,2 +1,3 @@ |
|||||
edlib |
edlib |
||||
python-dateutil |
python-dateutil |
||||
|
terminaltables |
||||
Write
Preview
Loading…
Cancel
Save
Reference in new issue