48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
import os
|
|
import pickle
|
|
try:
|
|
from UserDict import DictMixin
|
|
except ModuleNotFoundError:
|
|
from collections.abc import MutableMapping as DictMixin
|
|
|
|
# a small class to interpret a folder as an object
|
|
# with files as pickled items and/or attributes
|
|
class storage(DictMixin, object):
|
|
def __init__(self, path):
|
|
try:
|
|
os.makedirs(path)
|
|
except OSError as error:
|
|
if error.errno != 17:
|
|
raise error
|
|
object.__setattr__(self, '_path', path)
|
|
def keys(self):
|
|
return os.listdir(self._path)
|
|
def __getattr__(self, name):
|
|
path = os.path.join(self._path, name)
|
|
try:
|
|
with open(path, 'rb') as file:
|
|
value = pickle.load(file)
|
|
except Exception as e:
|
|
raise AttributeError(name,*e.args)
|
|
return value
|
|
def __setattr__(self, name, value):
|
|
path = os.path.join(self._path, name)
|
|
with open(path, 'wb') as file:
|
|
return pickle.dump(value, file, protocol=2)
|
|
def __delattr__(self, name):
|
|
path = os.path.join(self._path, name)
|
|
os.unlink(path)
|
|
def __getitem__(self, name):
|
|
try:
|
|
return getattr(self, name)
|
|
except AttributeError as e:
|
|
raise KeyError(name,*e.args)
|
|
def __setitem__(self, name, value):
|
|
return setattr(self, name, value)
|
|
def __delitem__(self, name):
|
|
return delattr(self, name)
|
|
def __iter__(self):
|
|
return iter(self.keys())
|
|
def __len__(self):
|
|
return len(self.keys())
|