52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""GUI 配置存储。"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
# 默认配置(云端服务器公网 IP 写死)
|
|
DEFAULTS = {
|
|
"server_url": "ws://8.137.99.82:9000/ws",
|
|
"worker_id": "worker-1",
|
|
"worker_name": "本机",
|
|
}
|
|
|
|
|
|
def get_config_path() -> str:
|
|
"""配置文件路径:项目根目录下的 client_config.json。"""
|
|
root = get_project_root()
|
|
return os.path.join(root, "client_config.json")
|
|
|
|
|
|
def load_config() -> dict:
|
|
"""加载配置。若为旧版本地地址则迁移为云端地址。"""
|
|
path = get_config_path()
|
|
if os.path.isfile(path):
|
|
try:
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
cfg = {**DEFAULTS, **data}
|
|
# 旧版本地地址迁移为云端地址
|
|
if cfg.get("server_url") == "ws://127.0.0.1:9000/ws":
|
|
cfg["server_url"] = DEFAULTS["server_url"]
|
|
return cfg
|
|
except Exception:
|
|
pass
|
|
return DEFAULTS.copy()
|
|
|
|
|
|
def save_config(data: dict) -> None:
|
|
"""保存配置。"""
|
|
path = get_config_path()
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
|
|
|
|
|
def get_project_root() -> str:
|
|
"""项目根目录。打包运行时为 exe 所在目录,否则为项目源码根目录。"""
|
|
if getattr(sys, "frozen", False):
|
|
return os.path.dirname(sys.executable)
|
|
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|