优化了很多问题。
This commit is contained in:
200
ConfigManager.py
Normal file
200
ConfigManager.py
Normal file
@@ -0,0 +1,200 @@
|
||||
import ujson
|
||||
import uos
|
||||
|
||||
class ConfigManager:
|
||||
def __init__(self, config_dir="configs"):
|
||||
"""
|
||||
初始化配置管理器
|
||||
:param config_dir: 配置文件存储的目录
|
||||
"""
|
||||
self.config_dir = config_dir
|
||||
self._ensure_dir_exists(config_dir)
|
||||
|
||||
def _ensure_dir_exists(self, directory):
|
||||
"""
|
||||
确保目录存在,如果不存在则创建
|
||||
:param directory: 目录路径
|
||||
"""
|
||||
try:
|
||||
uos.listdir(directory) # 尝试列出目录内容
|
||||
except OSError:
|
||||
uos.mkdir(directory) # 如果目录不存在,则创建
|
||||
|
||||
def _get_file_path(self, root_key):
|
||||
"""
|
||||
根据根键生成配置文件路径
|
||||
:param root_key: 配置的根键(如 'system')
|
||||
:return: 配置文件路径
|
||||
"""
|
||||
return f"{self.config_dir}/{root_key}.conf"
|
||||
|
||||
def _load_config(self, root_key):
|
||||
"""
|
||||
加载配置文件内容
|
||||
:param root_key: 配置的根键
|
||||
:return: 配置字典
|
||||
"""
|
||||
file_path = self._get_file_path(root_key)
|
||||
try:
|
||||
with open(file_path, "r") as f:
|
||||
return ujson.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
def _save_config(self, root_key, config):
|
||||
"""
|
||||
保存配置到文件
|
||||
:param root_key: 配置的根键
|
||||
:param config: 配置字典
|
||||
"""
|
||||
file_path = self._get_file_path(root_key)
|
||||
with open(file_path, "w") as f:
|
||||
ujson.dump(config, f)
|
||||
|
||||
def set(self, key, value):
|
||||
"""
|
||||
设置配置值
|
||||
:param key: 配置键,使用点分割(如 'system.wifi.name')
|
||||
:param value: 配置值
|
||||
"""
|
||||
keys = key.split(".")
|
||||
if len(keys) < 2:
|
||||
raise ValueError("Key must contain at least one dot (e.g., 'system.wifi.name')")
|
||||
|
||||
root_key = keys[0]
|
||||
sub_keys = keys[1:]
|
||||
|
||||
config = self._load_config(root_key)
|
||||
current = config
|
||||
|
||||
for sub_key in sub_keys[:-1]:
|
||||
if sub_key not in current or not isinstance(current[sub_key], dict):
|
||||
current[sub_key] = {}
|
||||
current = current[sub_key]
|
||||
|
||||
current[sub_keys[-1]] = value
|
||||
self._save_config(root_key, config)
|
||||
|
||||
def get(self, key, default=None):
|
||||
"""
|
||||
获取配置值
|
||||
:param key: 配置键,使用点分割(如 'system.wifi.name')
|
||||
:param default: 默认值,如果键不存在则返回
|
||||
:return: 配置值或默认值
|
||||
"""
|
||||
keys = key.split(".")
|
||||
if len(keys) < 2:
|
||||
raise ValueError("Key must contain at least one dot (e.g., 'system.wifi.name')")
|
||||
|
||||
root_key = keys[0]
|
||||
sub_keys = keys[1:]
|
||||
|
||||
config = self._load_config(root_key)
|
||||
current = config
|
||||
|
||||
for sub_key in sub_keys:
|
||||
if sub_key in current:
|
||||
current = current[sub_key]
|
||||
else:
|
||||
return default
|
||||
|
||||
return current
|
||||
|
||||
def delete(self, key):
|
||||
"""
|
||||
删除配置键
|
||||
:param key: 配置键,使用点分割(如 'system.wifi.name')
|
||||
"""
|
||||
keys = key.split(".")
|
||||
if len(keys) < 2:
|
||||
raise ValueError("Key must contain at least one dot (e.g., 'system.wifi.name')")
|
||||
|
||||
root_key = keys[0]
|
||||
sub_keys = keys[1:]
|
||||
|
||||
config = self._load_config(root_key)
|
||||
current = config
|
||||
|
||||
for sub_key in sub_keys[:-1]:
|
||||
if sub_key in current and isinstance(current[sub_key], dict):
|
||||
current = current[sub_key]
|
||||
else:
|
||||
return # Key does not exist, nothing to delete
|
||||
|
||||
if sub_keys[-1] in current:
|
||||
del current[sub_keys[-1]]
|
||||
self._save_config(root_key, config)
|
||||
|
||||
def clear(self, root_key):
|
||||
"""
|
||||
清空某个根键的配置文件
|
||||
:param root_key: 配置的根键(如 'system')
|
||||
"""
|
||||
file_path = self._get_file_path(root_key)
|
||||
try:
|
||||
uos.remove(file_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def append_to_list(self, key, value, append_to_end=True):
|
||||
"""
|
||||
在指定字典的列表值中追加数据
|
||||
:param key: 配置键,使用点分割(如 'system.wifi.list')
|
||||
:param value: 要追加的数据
|
||||
:param append_to_end: 是否追加到列表末尾,默认为 True;如果为 False,则追加到开头
|
||||
"""
|
||||
keys = key.split(".")
|
||||
if len(keys) < 2:
|
||||
raise ValueError("Key must contain at least one dot (e.g., 'system.wifi.list')")
|
||||
|
||||
root_key = keys[0]
|
||||
sub_keys = keys[1:]
|
||||
|
||||
config = self._load_config(root_key)
|
||||
current = config
|
||||
|
||||
for sub_key in sub_keys[:-1]:
|
||||
if sub_key not in current or not isinstance(current[sub_key], dict):
|
||||
current[sub_key] = {}
|
||||
current = current[sub_key]
|
||||
|
||||
list_key = sub_keys[-1]
|
||||
if list_key not in current or not isinstance(current[list_key], list):
|
||||
current[list_key] = []
|
||||
|
||||
if append_to_end:
|
||||
current[list_key].append(value)
|
||||
else:
|
||||
current[list_key].insert(0, value)
|
||||
|
||||
self._save_config(root_key, config)
|
||||
|
||||
def remove_from_list(self, key, value):
|
||||
"""
|
||||
从指定字典的列表值中删除数据
|
||||
:param key: 配置键,使用点分割(如 'system.wifi.list')
|
||||
:param value: 要删除的数据
|
||||
"""
|
||||
keys = key.split(".")
|
||||
if len(keys) < 2:
|
||||
raise ValueError("Key must contain at least one dot (e.g., 'system.wifi.list')")
|
||||
|
||||
root_key = keys[0]
|
||||
sub_keys = keys[1:]
|
||||
|
||||
config = self._load_config(root_key)
|
||||
current = config
|
||||
|
||||
for sub_key in sub_keys[:-1]:
|
||||
if sub_key not in current or not isinstance(current[sub_key], dict):
|
||||
current[sub_key] = {}
|
||||
current = current[sub_key]
|
||||
|
||||
list_key = sub_keys[-1]
|
||||
if list_key in current and isinstance(current[list_key], list):
|
||||
try:
|
||||
current[list_key].remove(value)
|
||||
except ValueError:
|
||||
pass
|
||||
self._save_config(root_key, config)
|
||||
|
||||
Reference in New Issue
Block a user