2023-05-11 21:23:51 +03:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import Any, Union
|
2023-05-11 21:19:46 +03:00
|
|
|
|
|
|
|
from ujson import dumps, loads
|
|
|
|
|
|
|
|
|
2023-05-11 21:23:51 +03:00
|
|
|
def json_read(path: Union[str, Path]) -> Any:
|
|
|
|
with open(str(path), mode="r", encoding="utf-8") as f:
|
2023-05-11 21:19:46 +03:00
|
|
|
data = f.read()
|
|
|
|
return loads(data)
|
|
|
|
|
|
|
|
|
2023-05-11 21:23:51 +03:00
|
|
|
def json_write(data: Any, path: Union[str, Path]) -> None:
|
|
|
|
with open(str(path), mode="w", encoding="utf-8") as f:
|
2023-05-11 21:19:46 +03:00
|
|
|
f.write(dumps(data, ensure_ascii=False, escape_forward_slashes=False, indent=4))
|
|
|
|
|
|
|
|
|
2023-05-11 21:23:51 +03:00
|
|
|
def config_get(key: str, *path: str, config_file: str = "config.json") -> Any:
|
|
|
|
this_key = json_read(config_file)
|
2023-05-11 21:19:46 +03:00
|
|
|
for dict_key in path:
|
|
|
|
this_key = this_key[dict_key]
|
|
|
|
return this_key[key]
|
|
|
|
|
|
|
|
|
2023-05-11 21:23:51 +03:00
|
|
|
def config_set(
|
|
|
|
key: str, value: Any, *path: str, config_file: str = "config.json"
|
|
|
|
) -> None:
|
|
|
|
this_dict = json_read(config_file)
|
2023-05-11 21:19:46 +03:00
|
|
|
string = "this_dict"
|
|
|
|
for arg in path:
|
|
|
|
string += f'["{arg}"]'
|
|
|
|
if type(value) in [str]:
|
|
|
|
string += f'["{key}"] = "{value}"'
|
|
|
|
else:
|
|
|
|
string += f'["{key}"] = {value}'
|
|
|
|
exec(string)
|
2023-05-11 21:23:51 +03:00
|
|
|
json_write(this_dict, config_file)
|
2023-05-11 21:19:46 +03:00
|
|
|
return
|