初始提交
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _get_app_dir():
|
||||
if getattr(sys, 'frozen', False):
|
||||
return os.path.dirname(sys.executable)
|
||||
return os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _get_config_path():
|
||||
return os.path.join(_get_app_dir(), "config.json")
|
||||
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"api": {
|
||||
"url": "http://localhost:8080/wallpaper",
|
||||
"mode": "direct",
|
||||
"json_image_field": "url",
|
||||
"timeout": 30,
|
||||
},
|
||||
"wallpaper": {
|
||||
"fill_style": "fill",
|
||||
"cache_dir": "./cache",
|
||||
"max_cache_files": 10,
|
||||
"show_notification": True,
|
||||
},
|
||||
"auto_refresh": {
|
||||
"enabled": False,
|
||||
"interval_minutes": 10,
|
||||
},
|
||||
}
|
||||
|
||||
_config = None
|
||||
|
||||
|
||||
def _resolve_path(path: str) -> str:
|
||||
if os.path.isabs(path):
|
||||
return path
|
||||
return os.path.normpath(os.path.join(_get_app_dir(), path))
|
||||
|
||||
|
||||
def load() -> dict:
|
||||
global _config
|
||||
if _config is not None:
|
||||
return _config
|
||||
config_path = _get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
_config = json.load(f)
|
||||
else:
|
||||
_config = DEFAULT_CONFIG
|
||||
merged = dict(DEFAULT_CONFIG)
|
||||
_deep_merge(merged, _config)
|
||||
_config = merged
|
||||
return _config
|
||||
|
||||
|
||||
def save(cfg: dict = None) -> None:
|
||||
global _config
|
||||
if cfg is not None:
|
||||
_config = cfg
|
||||
with open(_get_config_path(), "w", encoding="utf-8") as f:
|
||||
json.dump(_config, f, indent=4, ensure_ascii=False)
|
||||
|
||||
|
||||
def reload() -> dict:
|
||||
global _config
|
||||
_config = None
|
||||
return load()
|
||||
|
||||
|
||||
def get(path: str, default=None):
|
||||
cfg = load()
|
||||
keys = path.split(".")
|
||||
for k in keys:
|
||||
if isinstance(cfg, dict):
|
||||
cfg = cfg.get(k)
|
||||
if cfg is None:
|
||||
return default
|
||||
else:
|
||||
return default
|
||||
return cfg
|
||||
|
||||
|
||||
def set_(path: str, value):
|
||||
global _config
|
||||
cfg = load()
|
||||
keys = path.split(".")
|
||||
d = cfg
|
||||
for k in keys[:-1]:
|
||||
d = d.setdefault(k, {})
|
||||
d[keys[-1]] = value
|
||||
save(cfg)
|
||||
|
||||
|
||||
def _deep_merge(base, override):
|
||||
for key, value in override.items():
|
||||
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
|
||||
_deep_merge(base[key], value)
|
||||
else:
|
||||
base[key] = value
|
||||
Reference in New Issue
Block a user