forked from Aniketc068/MX-Signer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_loader.py
More file actions
72 lines (62 loc) · 2.46 KB
/
config_loader.py
File metadata and controls
72 lines (62 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import json
import os
import logging
# Set up logging
logging.basicConfig(
filename='MX_Signer.log',
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%d-%b-%Y %H:%M:%S'
)
# Constants for configuration directory and file
CONFIG_DIR = os.path.expanduser('~/Documents/MX_Signer/')
CONFIG_FILE = os.path.join(CONFIG_DIR, 'managex_signer.config')
def ensure_config_dir():
"""Ensure the configuration directory exists. If not, create it."""
if not os.path.exists(CONFIG_DIR):
try:
os.makedirs(CONFIG_DIR) # Create the directory
logging.info(f"Created configuration directory: {CONFIG_DIR}")
except Exception as e:
logging.exception(f"Error creating configuration directory '{CONFIG_DIR}': {e}")
raise
def load_config():
"""Load configuration from the config file or generate a new one with defaults."""
# Default config values
default_config = {
"FLASK_HOST": "127.0.0.1",
"FLASK_PORT": 5000
}
# Ensure the config directory exists
ensure_config_dir()
# Check if the config file exists
if not os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(default_config, f, indent=4) # Write default config to file
logging.info(f"Config file '{CONFIG_FILE}' created with default values.")
except Exception as e:
logging.exception(f"Error creating config file '{CONFIG_FILE}': {e}")
raise
return default_config
# If config file exists, attempt to load it
try:
with open(CONFIG_FILE, 'r') as f:
config = json.load(f) # Load the JSON config
# Validate and merge missing defaults
for key, value in default_config.items():
if key not in config:
logging.warning(f"Missing key '{key}' in config file. Adding default value.")
config[key] = value
return config
except Exception as e:
logging.exception(f"Error loading config file '{CONFIG_FILE}': {e}")
raise
def get_config_value(key, default=None):
"""Retrieve a specific configuration value with a default fallback."""
try:
config = load_config()
return config.get(key, default) # Retrieve the value or fallback to the default
except Exception as e:
logging.error(f"Error retrieving config value for key '{key}': {e}")
return default