Better persistence

This commit is contained in:
Remy Moll
2020-12-10 18:25:33 +01:00
parent cd13cea967
commit 6f80f26de1
11 changed files with 208 additions and 276 deletions

View File

@@ -1 +0,0 @@
# Placeholder

View File

@@ -1,21 +0,0 @@
{
"bot" : {
"messages_read": 0,
"messages_sent": 0,
"commands_executed": 0,
"photos_sent": 0,
"log": [],
"chat_members": {},
"reboots": 0
},
"clock" : {
"test":""
},
"dashboard" : {
"test":""
},
"global" : {
"shopping_list" : []
}
}

View File

@@ -1,83 +0,0 @@
import json
import time
import os
import shutil
class Variables():
""""""
def __init__(self, module_name, file_name="persistence/persistent_vars.json", init_name="persistence/persistent_init.json", ):
self.path = file_name
self.init_path = init_name
self.module = module_name
self.last_action = ""
# last performed action, if only reads are made, then the underlying var has not been changed
# and doesn't need to be read again
self.savefile = {}
if not os.path.exists(self.path):
shutil.copy(self.init_path, self.path)
def global_action(self, action, name, value=""):
old = self.module
self.module = "global"
action = getattr(self, action)
if value != "":
ret = action(name,value)
else:
ret = action(name)
self.module = old
return ret
def write(self, name, value):
pre = self.read("")
pre[self.module][name] = value
try:
file = open(self.path,"w")
json.dump(pre, file)
file.close()
self.last_action = "write"
except:
print("Config not written - critical")
def read(self, name):
if self.last_action == "read":
vars = self.savefile
else:
file = open(self.path,"r")
vars = json.load(file)
file.close()
self.savefile = vars
self.last_action = "read"
if name != "":
vars = vars[self.module][name]
return vars
def increment(self, name, inc=1):
pre = self.read(name)
if pre:
self.write(name, pre + inc)
else:
self.write(name, inc)
def append_list(self, name, value):
pre = self.read(name)
pre.append(value)
self.write(name, pre)
def read_ext_file(self, path):
"""returns content of given file"""
if not os.path.exists(path):
return "File does not exist"
file = open(path,"r")
content = file.read()
file.close()
return content