Esempio n. 1
0
 def __init__(self, root, protocol=1):
     """ Return a db object that will manage the specied directory"""
     self.root = Path(root).expanduser().abspath()
     self.protocol = protocol
     if not self.root.isdir():
         self.root.makedirs()
     # cache has { 'key' : (obj, orig_mod_time) }
     self.cache = {}
Esempio n. 2
0
class PickleShareDB(UserDict.DictMixin):
    """ The main 'connection' object for PickleShare database """

    def __init__(self, root, protocol=1):
        """ Return a db object that will manage the specied directory"""
        self.root = Path(root).expanduser().abspath()
        self.protocol = protocol
        if not self.root.isdir():
            self.root.makedirs()
        # cache has { 'key' : (obj, orig_mod_time) }
        self.cache = {}

    def __getitem__(self, key):
        """ db['key'] reading """
        fil = self.root / key
        try:
            mtime = fil.stat()[stat.ST_MTIME]
        except OSError:
            raise KeyError(key)

        if fil in self.cache and mtime == self.cache[fil][1]:
            return self.cache[fil][0]
        try:
            # The cached item has expired, need to read
            obj = pickle.load(fil.open())
        except:
            raise KeyError(key)

        self.cache[fil] = (obj, mtime)
        return obj

    def __setitem__(self, key, value):
        """ db['key'] = 5 """
        fil = self.root / key
        parent = fil.parent
        if parent and not parent.isdir():
            parent.makedirs()
        pickled = pickle.dump(value, fil.open("w"), protocol=self.protocol)
        try:
            self.cache[fil] = (value, fil.mtime)
        except OSError, e:
            if e.errno != 2:
                raise