-
Alice Brenon authoreddeabb234
store.py 1.39 KiB
import os
import os.path
def preparePath(template, **kwargs):
path = template.format(**kwargs)
os.makedirs(os.path.dirname(path), exist_ok=True)
return path
class Cache:
ROOT = "cache"
def __init__(self, loader, pathPolicy=lambda *args:str(args)
, serializer=None, unserializer=None):
self.RAM = {}
self.loader = loader
self.pathPolicy = pathPolicy
self.serializer = serializer
self.unserializer = unserializer
def __call__(self, *args):
symbolicPath = self.pathPolicy(*args)
self.heat(symbolicPath)
if symbolicPath not in self.RAM:
self.RAM[symbolicPath] = self.loader(*args)
self.save(symbolicPath)
return self.RAM[symbolicPath]
def heat(self, symbolicPath):
if self.unserializer and symbolicPath not in self.RAM:
path = "{root}/{path}".format(root=Cache.ROOT, path=symbolicPath)
if os.path.isfile(path):
with open(path, 'r') as f:
self.RAM[symbolicPath] = self.unserializer(f)
def save(self, symbolicPath):
if self.serializer and symbolicPath in self.RAM:
path = preparePath("{root}/{path}", root=Cache.ROOT, path=symbolicPath)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
self.serializer(self.RAM[symbolicPath], f)