jiateng_ws/utils/config_loader.py

166 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()
def get_config(self, key):
"""
获取serial配置下的指定配置
Args:
key: 配置键,例如'mdz', 'cz'
Returns:
dict: 配置值未找到则返回None
"""
if 'serial' not in self.config:
self.config['serial'] = {}
if key not in self.config['serial']:
return None
return self.config['serial'][key]
def set_config(self, key, config_data):
"""
设置serial配置下的指定配置
Args:
key: 配置键,例如'mdz', 'cz'
config_data: 要设置的配置数据
Returns:
bool: 是否设置成功
"""
if 'serial' not in self.config:
self.config['serial'] = {}
self.config['serial'][key] = config_data
# 这里不保存配置等待调用save_config方法时一并保存
return True