-
-
Save bingal/6ae18ec19bb11c6c6ad2b03691b2d0c7 to your computer and use it in GitHub Desktop.
更优雅的方式使用lmdb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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