-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_keyval.py
More file actions
50 lines (41 loc) · 1.13 KB
/
file_keyval.py
File metadata and controls
50 lines (41 loc) · 1.13 KB
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
'''
Implements a KeyVal Store where a local file is the backend
'''
import json
import os
class FileKeyVal(object):
def __init__(self, name, **options):
self.options = options
self.filename = f'.pykeyval_{name}'
self.path = options.get('path') or self.filename
def _read(self):
with open(self.path, 'r') as f:
data = f.read()
if data:
return json.loads(data)
else:
return dict()
def _write(self, data):
with open(self.path, 'w') as f:
f.write(json.dumps(data))
def get(self, key):
data = self._read()
return data.get(key)
def set(self, key, val):
if os.path.isfile(self.path):
data = self._read()
else:
data = dict()
data[key] = val
self._write(data)
return True
def delete(self, key):
data = self._read()
if key in data.keys():
del data[key]
self._write(data)
return True
return False
def clear(self):
open(self.path, 'w').close()
return True