mirror of
https://github.com/KenanZhu/AutoLibrary.git
synced 2026-06-18 07:23:03 +08:00
optimize(ConfigReader, ConfigWriter): 优化配置文件读写类逻辑,完善异常处理,添加注释文档
This commit is contained in:
+44
-18
@@ -8,63 +8,89 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
|||||||
See the LICENSE file for details.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
import copy
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
class ConfigReader:
|
class ConfigReader:
|
||||||
|
"""
|
||||||
|
Config reader class.
|
||||||
|
|
||||||
|
This class is used to read config file in JSON format.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config_path (str): The path of config file.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> print(open("config.json", "r", encoding="utf-8").read())
|
||||||
|
{
|
||||||
|
"key1": {
|
||||||
|
"key2": "value1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
>>> config_reader = ConfigReader("config.json")
|
||||||
|
>>> config_reader.get("key1/key2")
|
||||||
|
"value1"
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
config_path: str
|
config_path: str
|
||||||
):
|
):
|
||||||
|
|
||||||
self._config_path = config_path
|
self.__config_path = config_path
|
||||||
self._config_data = {}
|
self.__config_data = None
|
||||||
if not self.__readConfig():
|
self.__readConfig()
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def __readConfig(
|
def __readConfig(
|
||||||
self
|
self
|
||||||
) -> bool:
|
):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(self._config_path, 'r', encoding='utf-8') as file:
|
with open(self.__config_path, 'r', encoding='utf-8') as file:
|
||||||
self._config_data = json.load(file)
|
self.__config_data = json.load(file)
|
||||||
return True
|
except FileNotFoundError as e:
|
||||||
|
raise Exception(f"Config file not found: {self.__config_path}") from e
|
||||||
|
except PermissionError as e:
|
||||||
|
raise Exception(f"Without enough permission to read config file: {self.__config_path}") from e
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
raise Exception(f"JSON decode error in config file: {self.__config_path}") from e
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error reading config file: {e}")
|
raise Exception(f"Unknown error occurred while reading config file: {e}") from e
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def getConfigs(
|
def getConfigs(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
|
|
||||||
return self._config_data.copy()
|
return self.__config_data.copy()
|
||||||
|
|
||||||
|
|
||||||
def getConfig(
|
def getConfig(
|
||||||
self,
|
self,
|
||||||
key: str
|
key: str
|
||||||
) -> dict:
|
) -> Any:
|
||||||
|
|
||||||
return self._config_data.get(key, {})
|
config = self.__config_data.get(key, {})
|
||||||
|
return copy.deepcopy(config)
|
||||||
|
|
||||||
|
|
||||||
def get(
|
def get(
|
||||||
self,
|
self,
|
||||||
key: str,
|
key: str,
|
||||||
default: any = None
|
default: Any = None
|
||||||
) -> any:
|
) -> Any:
|
||||||
|
|
||||||
keys = key.split('/')
|
keys = key.split('/')
|
||||||
current = self._config_data
|
current = self.__config_data
|
||||||
for k in keys:
|
for k in keys:
|
||||||
if isinstance(current, dict) and k in current:
|
if isinstance(current, dict) and k in current:
|
||||||
current = current[k]
|
current = current[k]
|
||||||
else:
|
else:
|
||||||
return default
|
return default
|
||||||
return current
|
return copy.deepcopy(current)
|
||||||
|
|
||||||
|
|
||||||
def hasConfig(
|
def hasConfig(
|
||||||
@@ -86,4 +112,4 @@ class ConfigReader:
|
|||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
||||||
return self._config_path
|
return self.__config_path
|
||||||
|
|||||||
+40
-11
@@ -9,8 +9,35 @@ See the LICENSE file for details.
|
|||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
class ConfigWriter:
|
class ConfigWriter:
|
||||||
|
"""
|
||||||
|
Config writer class.
|
||||||
|
|
||||||
|
This class is used to write config file in JSON format.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config_path (str): The path of config file.
|
||||||
|
config_data (dict): The config data to be written.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> config_data = {
|
||||||
|
... "key1": {
|
||||||
|
... "key2": "value1"
|
||||||
|
... }
|
||||||
|
... }
|
||||||
|
>>> config_writer = ConfigWriter("config.json", config_data)
|
||||||
|
>>> config_writer.set("key1/key2", "value1")
|
||||||
|
True
|
||||||
|
>>> print(open("config.json", "r", encoding="utf-8").read())
|
||||||
|
{
|
||||||
|
"key1": {
|
||||||
|
"key2": "value1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -19,23 +46,25 @@ class ConfigWriter:
|
|||||||
):
|
):
|
||||||
|
|
||||||
self.__config_path = config_path
|
self.__config_path = config_path
|
||||||
self.__config_data = config_data if config_data is not None else {}
|
self.__config_data = config_data.copy() if config_data is not None else {}
|
||||||
if config_data is None:
|
self.__writeConfig()
|
||||||
return None
|
|
||||||
if not self.__writeConfig():
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def __writeConfig(
|
def __writeConfig(
|
||||||
self
|
self
|
||||||
) -> bool:
|
):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(self.__config_path, "w") as f:
|
with open(self.__config_path, "w", encoding="utf-8") as f:
|
||||||
json.dump(self.__config_data, f, indent=4, sort_keys=False)
|
json.dump(self.__config_data, f, indent=4, sort_keys=False)
|
||||||
return True
|
except PermissionError as e:
|
||||||
except:
|
raise Exception(f"Without enough permission to write config file: {self.__config_path}") from e
|
||||||
return False
|
except IOError as e:
|
||||||
|
raise Exception(f"IO error occurred while writing config file: {self.__config_path}") from e
|
||||||
|
except TypeError as e:
|
||||||
|
raise Exception(f"Config data contains invalid type that can not be JSON serialized: {e}") from e
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Unknown error occurred while writing config file: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
def setConfigs(
|
def setConfigs(
|
||||||
@@ -60,7 +89,7 @@ class ConfigWriter:
|
|||||||
def set(
|
def set(
|
||||||
self,
|
self,
|
||||||
key: str,
|
key: str,
|
||||||
value: dict
|
value: Any
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
keys = key.replace("\\", "/").split("/")
|
keys = key.replace("\\", "/").split("/")
|
||||||
|
|||||||
Reference in New Issue
Block a user