aboutsummaryrefslogtreecommitdiffstats
path: root/config.py
diff options
context:
space:
mode:
authornico <nico@magicbroccoli.de>2020-02-16 20:19:03 +0100
committernico <nico@magicbroccoli.de>2020-02-16 20:19:03 +0100
commitf02b7e87eddaba1935fb72f26b9dec4b40cb1ac0 (patch)
tree04a7d2cdf24673306841fbc443b6a0dc31f14b06 /config.py
parent7c656961ce8182dd58ae5265fe01f644f75fa4cf (diff)
utilize /etc/ directory
+ add config.py to read / touch create the etc config file
Diffstat (limited to 'config.py')
-rw-r--r--config.py66
1 files changed, 66 insertions, 0 deletions
diff --git a/config.py b/config.py
new file mode 100644
index 0000000..55b7639
--- /dev/null
+++ b/config.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import sys
+from pathlib import Path
+
+
+class Config:
+ def __init__(self):
+ # global config path
+ conf_path = '/etc/ejabberd-metrics.conf'
+ self.file = Path(conf_path)
+ self.content = None
+
+ # read config file
+ self._read()
+
+ def _read(self):
+ """init the config object with this method"""
+ self._check()
+
+ # open and load json content from config
+ with open(self.file, 'r', encoding='utf-8') as f:
+ try:
+ self.content = json.load(f)
+
+ # catch json decoding errors
+ except json.JSONDecodeError as err:
+ print(err, file=sys.stderr)
+ exit(1)
+
+ def _check(self):
+ """internal method to check if the config file exists"""
+ try:
+ # if file is present try to read it's contents
+ if self.file.exists():
+ return
+
+ # if not create a blank file
+ else:
+ Path.touch(self.file)
+
+ # catch permission exceptions as this tries to write to /etc/
+ except PermissionError as err:
+ print(err, file=sys.stderr)
+ sys.exit(err.errno)
+
+ def get(self, key: str = None, default: (str, int) = None) -> (dict, str, int, None):
+ """method to retrieve the whole config data, a single value or the optional default value"""
+ # if a special key is request, return only that value
+ if key is not None:
+
+ # safety measure
+ if key in self.content:
+ return self.content[key]
+
+ # if a default value is given return that
+ if default is not None:
+ return default
+
+ # if the key isn't part if self.content return None
+ else:
+ return None
+
+ # else return everything
+ return self.content