-
Notifications
You must be signed in to change notification settings - Fork 6
/
storage.py
67 lines (55 loc) · 1.55 KB
/
storage.py
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
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-
# vim:set ts=8 sts=8 sw=8 tw=80 noet cc=80:
import os
import json
from module import Module, CONFIG, COMMAND
class Storage(Module):
def __init__(self, filename, **keywords):
super(Storage, self).__init__([CONFIG, COMMAND], **keywords)
self.values = {}
self.filename = filename
if os.path.isfile(filename):
self.load()
self.save()
def load(self):
with open(self.filename, "r") as f:
self.values = json.loads(f.read())
def save(self):
with open(self.filename, "w") as f:
f.write(json.dumps(self.values))
def command(self, cmd, **keywords):
if cmd == 'get_config':
if 'key' in keywords:
key = keywords['key']
value = None
if "default" in keywords:
value = keywords["default"]
if key in self.values:
value = self.values[key]
self.send_cmd('config_value', key=key,
value=value)
else:
self.publish_all()
elif cmd == 'init_config':
key = keywords['key']
value = keywords['value']
if not key in self.values:
self.__setitem__(key, value)
def config_change(self, key, value):
self.log.debug("config change: '%s'='%s'" % (key, value))
self.__setitem__(key, value)
def reload_config(self):
self.load()
self.publish_all()
def publish_all(self):
self.send_cmd('config_values', value=self.values)
def __getitem__(self, key):
return self.values[key]
def __setitem__(self, key, value):
self.values[key] = value
self.save()
def __getattr__(self, key):
return self.values[key]
def __setattr_(self, key, value):
self.values[key] = value
self.save()