46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
import json
|
|
from pathlib import Path
|
|
import logging
|
|
|
|
logger = logging.getLogger('iottb.config')
|
|
|
|
|
|
class Config:
|
|
DEFAULT_CONFIG = {
|
|
"database_path": "~/.iottb.db",
|
|
"log_level": "INFO"
|
|
}
|
|
|
|
def __init__(self, config_file=None):
|
|
self.config_file = Path(config_file or "config.json")
|
|
if not self.config_file.exists():
|
|
self.create_default_config()
|
|
else:
|
|
self.config = self.load_config()
|
|
|
|
def create_default_config(self):
|
|
try:
|
|
self.save_config(self.DEFAULT_CONFIG)
|
|
except (IsADirectoryError, PermissionError) as e:
|
|
logger.error(f"Error creating default config: {e}")
|
|
raise
|
|
|
|
def load_config(self):
|
|
try:
|
|
with open(self.config_file, "r") as file:
|
|
return json.load(file)
|
|
except IsADirectoryError as e:
|
|
logger.error(f"Error loading config: {e}")
|
|
raise
|
|
except PermissionError as e:
|
|
logger.error(f"Error loading config: {e}")
|
|
raise
|
|
|
|
def save_config(self, config):
|
|
try:
|
|
with open(self.config_file, "w") as f:
|
|
json.dump(config, f, indent=2)
|
|
except (IsADirectoryError, PermissionError) as e:
|
|
logger.error(f"Error saving config: {e}")
|
|
raise
|