websoft9/appmanage/api/settings/settings.py

70 lines
1.8 KiB
Python
Raw Normal View History

2023-08-26 18:20:30 +08:00
from api.utils.log import myLogger
2023-08-23 17:57:23 +08:00
from api.utils.helper import Singleton
__all__ = ['settings']
class Settings(object):
__metaclass__ = Singleton
def __init__(self):
self._config = {}
self.config_file = '/usr/src/app/config/settings.conf'
2023-08-24 13:51:30 +08:00
def build_config(self):
2023-08-23 17:57:23 +08:00
try:
2023-08-24 13:51:30 +08:00
with open(self.config_file, 'r') as f:
2023-08-23 17:57:23 +08:00
data = f.readlines()
2023-08-24 13:51:30 +08:00
except Exception as e:
2023-08-23 17:57:23 +08:00
data = []
for i in data:
2023-08-24 13:51:30 +08:00
if i.startswith('#'):
continue
2023-08-23 17:57:23 +08:00
i = i.replace('\n', '').replace('\r\n', '')
2023-08-24 15:47:46 +08:00
if not i:
continue
tmp = i.split('=')
if len(tmp) != 2:
myLogger.error_logger(f'invalid format {i}')
continue
2023-08-23 17:57:23 +08:00
key, value = i.split('=')
if self._config.get(key) != value:
self._config[key] = value
2023-08-24 13:51:30 +08:00
return self._config
def init_config_from_file(self, config_file: str=None):
if config_file:
self.config_file = config_file
self.build_config()
2023-08-23 17:57:23 +08:00
def update_setting(self, key: str, value: str):
self._config[key] = value
self.flush_config()
def get_setting(self, key: str, default=None):
return self._config.get(key, default)
2023-08-24 13:51:30 +08:00
def list_all_settings(self) -> dict:
self.build_config()
2023-08-23 17:57:23 +08:00
return self._config
def delete_setting(self, key: str, value: str):
2023-08-24 13:51:30 +08:00
if self._config.get(key) == value:
2023-08-23 17:57:23 +08:00
del self._config[key]
2023-08-24 13:51:30 +08:00
self.flush_config()
2023-08-23 17:57:23 +08:00
def flush_config(self):
2023-08-24 13:51:30 +08:00
try:
with open(self.config_file, 'w') as f:
for key, value in self._config.items():
f.write(f'{key}={value}\n')
except Exception as e:
myLogger.error_logger(e)
2023-08-23 17:57:23 +08:00
settings = Settings()