moved config to a json, which makes adding more variables easier, but perhaps otherwise adds complexity
This commit is contained in:
54
forum/db/config.py
Normal file
54
forum/db/config.py
Normal file
@@ -0,0 +1,54 @@
|
||||
import json
|
||||
import shutil
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self.config_values = [
|
||||
"version",
|
||||
"server_name",
|
||||
"server_description",
|
||||
"secret_key",
|
||||
"captcha_key",
|
||||
"registration_enabled",
|
||||
"login_required",
|
||||
"threads_per_page",
|
||||
"user_css",
|
||||
]
|
||||
self._update_class(self._read_values())
|
||||
|
||||
def get_config(self):
|
||||
current = self._read_values()
|
||||
self._update_class(current)
|
||||
return self
|
||||
|
||||
def set_config(self, **kwargs):
|
||||
for key in kwargs:
|
||||
if key not in self.config_values:
|
||||
raise ValueError(f"Unknown config key {key}!")
|
||||
|
||||
current = self._read_values()
|
||||
current.update(kwargs)
|
||||
self._update_class(current)
|
||||
self._write_values(current)
|
||||
|
||||
def set_config_secrets(self, secret_key, captcha_key):
|
||||
current = self._read_values()
|
||||
current["secret_key"] = secret_key
|
||||
current["captcha_key"] = captcha_key
|
||||
self._update_class(current)
|
||||
self._write_values(current)
|
||||
|
||||
def _read_values(self):
|
||||
with open(self.path, "rt") as fp:
|
||||
return json.load(fp)
|
||||
|
||||
def _write_values(self, values):
|
||||
shutil.copy(self.path, self.path + ".bkp")
|
||||
with open(self.path, "wt") as fp:
|
||||
json.dump(values, fp, indent=2, sort_keys=True)
|
||||
|
||||
def _update_class(self, values):
|
||||
for item in values:
|
||||
setattr(self, item, values[item])
|
||||
Reference in New Issue
Block a user