Posts python硬盘版kvdb,更优雅的方式使用lmdb
Post
Cancel

python硬盘版kvdb,更优雅的方式使用lmdb

经常需要保存些程序执行的状态,使用redis等服务有点太重了,发现了轻量级的kv数据库lmdb,但是直接使用有点麻烦,简单实现了个包装类。

用法:

1
2
3
4
5
6
7
8
9
10
11
12
# 写数据
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)

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/python
# encoding: utf-8
# author: bingal
# descryption: 更优雅的方式使用lmdb

import lmdb


class KVDB:
    def __init__(self, path=None, size=100*1024*1024):
        # 默认100MB
        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)


代码gist地址


邀请您关注我的公众号,我将会不时地为您推送独家原创的技术内容分享。
This post is licensed under CC BY 4.0 by the author.

Trending Tags