Compare commits

...

2 commits

Author SHA1 Message Date
84064261c1 Update 2025-04-09 23:32:27 +02:00
ec6a18ee8e Added Settings handler 2025-04-09 23:32:20 +02:00
3 changed files with 66 additions and 1 deletions

View file

@ -1,3 +1,5 @@
# python-lib-CBMF # python-lib-CBMF
This will become a collection of different python libs This will become a collection of different python libs
It begins with a function for handling settings file.

3
src/settings/__init__.py Normal file
View file

@ -0,0 +1,3 @@
from .main import HandleSettings
__version__ = "0.0.1"

60
src/settings/main.py Normal file
View file

@ -0,0 +1,60 @@
import yaml
class HandleSettings:
def __init__(self, path):
self.file = path
def read_settings(self, entry_name):
"""Read a specific entry from the settings file."""
data = self._read_file()
if data != None and entry_name in data:
return data[entry_name]
else:
return None
def _read_file(self):
"""Read from the yaml file."""
try:
with open(self.file, "r") as file:
data = yaml.safe_load(file)
return data
except (FileNotFoundError, PermissionError) as e:
print(f"Error loading settings file: {e}")
return None
def save_settings(self, entry_name, datadict):
"""Save the settings file, update a desired section."""
data = self._read_file()
if data != None:
data[entry_name] = datadict
else:
data = dict()
data[entry_name] = datadict
task = self._write_file(data)
return task
def _write_file(self, data):
"""Write dict to yaml file."""
try:
with open(self.file, "w") as file:
yaml.dump(data, file)
return True
except PermissionError as e:
print(f"Error saving setings: {e}")
return False
def delete_entry(self, entry_name):
"""Deletes and specific entry from the entire settings file/dict."""
data = self._read_file()
if data != None and entry_name in data:
del data[entry_name]
self._write_file(data)
return True
else:
return False
def purge_settings(self):
"""Inserts an empty dict."""
task = self._write_file(dict())
return task