Skip to content

Instantly share code, notes, and snippets.

@bingal

bingal/kvdb.py Secret

Last active April 15, 2022 09:41
Show Gist options
  • Save bingal/6ae18ec19bb11c6c6ad2b03691b2d0c7 to your computer and use it in GitHub Desktop.
Save bingal/6ae18ec19bb11c6c6ad2b03691b2d0c7 to your computer and use it in GitHub Desktop.
更优雅的方式使用lmdb
class KVDB:
def __init__(self, path=None, size=1024*1024*1024):
# 1GB
self.env = lmdb.open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'lmdb') if not path else path,
map_size=size)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return self.close()
def set(self, sid, name):
txn = self.env.begin(write=True)
txn.put(str(sid).encode(), name.encode())
txn.commit()
def delete(self, sid):
txn = self.env.begin(write=True)
txn.delete(str(sid).encode())
txn.commit()
def get(self, sid):
txn = self.env.begin()
name = txn.get(str(sid).encode())
return name.decode() if name else ''
def cursor(self):
txn = self.env.begin()
cur = txn.cursor()
return cur
def close(self):
self.env.close()
if __name__ == '__main__':
with KVDB() as kvdb:
kvdb.set('abc', 'bingal')
with KVDB() as kvdb:
print(kvdb.get('abc'))
with KVDB() as kvdb:
for key, value in kvdb.cursor():
print(key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment