bottle 0.5中的key-value数据库
import anydbm as dbm import cPickle as pickle class BottleBucket(object): '''Memory-caching wrapper around anydbm''' def __init__(self, name): self.__dict__['name'] = name self.__dict__['db'] = dbm.open('%s.db' % name, 'c') self.__dict__['mmap'] = {} def __getitem__(self, key): if key not in self.mmap: self.mmap[key] = pickle.loads(self.db[key]) return self.mmap[key] def __setitem__(self, key, value): self.mmap[key] = value def __delitem__(self, key): if key in self.mmap: del self.mmap[key] del self.db[key] def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError: raise AttributeError(key) def __iter__(self): return iter(self.ukeys()) def __contains__(self, key): return key in self.ukeys() def __len__(self): return len(self.ukeys()) def keys(self): return list(self.ukeys()) def ukeys(self): return set(self.db.keys()) | set(self.mmap.keys()) def save(self): self.close() self.__init__(self.name) def close(self): for key in self.mmap.keys(): pvalue = pickle.dumps(self.mmap[key], pickle.HIGHEST_PROTOCOL) if key not in self.db or pvalue != self.db[key]: self.db[key] = pvalue self.mmap.clear() self.db.close() def clear(self): for key in self.db.keys(): del self.db[key] self.mmap.clear() def update(self, other): self.mmap.update(other) def get(self, key, default=None): try: return self[key] except KeyError: if default: return default raise bb = BottleBucket("testbucket") # 打开testbucket.db,读取其中内容。若testbucket.db不存在,则会创建一个。 print bb.a # 读取其中的内容 print bb["b"] # 另一种读取方式 bb.c = 999 # 更新(增加)内容 bb["d"]=666 # 另一种更新方式 bb.save() # 将数据pickle后保存到testbucket.db中,数据类型支持Python对象。