Skip to content

Instantly share code, notes, and snippets.

@ianfiske
Created January 21, 2015 15:12
Show Gist options
  • Save ianfiske/9bfcd388dcd592d976e4 to your computer and use it in GitHub Desktop.
Save ianfiske/9bfcd388dcd592d976e4 to your computer and use it in GitHub Desktop.
Python wrapper class for keyval stores and pyrocksdb
import cPickle
import rocksdb
class KeyValDB(object):
@staticmethod
def get_database(db_type, path):
if db_type == 'shelve':
return ShelveDB(path)
elif db_type == 'rocksdb':
return RocksDB(path)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self.close()
except AttributeError:
print 'Not closeable.'
return True
class RocksDB(KeyValDB):
def __init__(self, fn):
self.db = rocksdb.DB(fn, rocksdb.Options(create_if_missing=True))
def __getitem__(self, item):
val_str = self.db.get(item)
val = cPickle.loads(val_str)
return val
def __setitem__(self, key, value):
self.db.put(key, cPickle.dumps(value, protocol=2))
def has_key(self, key):
return self.db.get(key) is not None
def close(self):
del self.db
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment