130 lines
4.0 KiB
Python
130 lines
4.0 KiB
Python
import os
|
|
import json
|
|
import logging
|
|
|
|
class ConfigLoader:
|
|
"""配置加载器,用于加载和管理应用配置"""
|
|
|
|
_instance = None
|
|
|
|
@classmethod
|
|
def get_instance(cls):
|
|
"""获取单例实例"""
|
|
if cls._instance is None:
|
|
cls._instance = ConfigLoader()
|
|
return cls._instance
|
|
|
|
def __init__(self):
|
|
"""初始化配置加载器"""
|
|
self.config = {}
|
|
self.config_file = os.path.join('config', 'app_config.json')
|
|
|
|
# 创建配置目录(如果不存在)
|
|
os.makedirs('config', exist_ok=True)
|
|
|
|
# 加载配置
|
|
self.load_config()
|
|
|
|
def load_config(self):
|
|
"""加载配置文件"""
|
|
try:
|
|
if os.path.exists(self.config_file):
|
|
with open(self.config_file, 'r', encoding='utf-8') as f:
|
|
self.config = json.load(f)
|
|
logging.info(f"已加载配置文件: {self.config_file}")
|
|
else:
|
|
# 创建默认配置
|
|
self.config = {
|
|
"app": {
|
|
"name": "腾智微丝产线包装系统",
|
|
"version": "1.0.0",
|
|
"features": {
|
|
"enable_serial_ports": False,
|
|
"enable_keyboard_listener": False
|
|
}
|
|
},
|
|
"database": {
|
|
"type": "sqlite",
|
|
"path": "db/jtDB.db",
|
|
"host": "",
|
|
"port": "",
|
|
"user": "",
|
|
"password": "",
|
|
"name": ""
|
|
}
|
|
}
|
|
|
|
# 保存默认配置
|
|
self.save_config()
|
|
logging.info(f"已创建默认配置文件: {self.config_file}")
|
|
except Exception as e:
|
|
logging.error(f"加载配置文件失败: {e}")
|
|
# 使用默认配置
|
|
self.config = {
|
|
"app": {
|
|
"name": "腾智微丝产线包装系统",
|
|
"version": "1.0.0",
|
|
"features": {
|
|
"enable_serial_ports": False,
|
|
"enable_keyboard_listener": False
|
|
}
|
|
}
|
|
}
|
|
|
|
def save_config(self):
|
|
"""保存配置到文件"""
|
|
try:
|
|
with open(self.config_file, 'w', encoding='utf-8') as f:
|
|
json.dump(self.config, f, indent=4, ensure_ascii=False)
|
|
logging.info(f"已保存配置文件: {self.config_file}")
|
|
return True
|
|
except Exception as e:
|
|
logging.error(f"保存配置文件失败: {e}")
|
|
return False
|
|
|
|
def get_value(self, key_path, default=None):
|
|
"""
|
|
获取配置值
|
|
|
|
Args:
|
|
key_path: 配置键路径,例如 "app.features.enable_serial_ports"
|
|
default: 默认值,如果配置项不存在则返回此值
|
|
|
|
Returns:
|
|
配置值或默认值
|
|
"""
|
|
keys = key_path.split('.')
|
|
value = self.config
|
|
|
|
try:
|
|
for key in keys:
|
|
value = value[key]
|
|
return value
|
|
except (KeyError, TypeError):
|
|
return default
|
|
|
|
def set_value(self, key_path, value):
|
|
"""
|
|
设置配置值
|
|
|
|
Args:
|
|
key_path: 配置键路径,例如 "app.features.enable_serial_ports"
|
|
value: 要设置的值
|
|
|
|
Returns:
|
|
bool: 是否设置成功
|
|
"""
|
|
keys = key_path.split('.')
|
|
config = self.config
|
|
|
|
# 遍历路径中的所有键,除了最后一个
|
|
for key in keys[:-1]:
|
|
if key not in config:
|
|
config[key] = {}
|
|
config = config[key]
|
|
|
|
# 设置最后一个键的值
|
|
config[keys[-1]] = value
|
|
|
|
# 保存配置
|
|
return self.save_config() |