45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
"""打印机配置管理 — JSON 文件持久化"""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
CONFIG_DIR = Path(__file__).resolve().parent.parent.parent / "data"
|
|
CONFIG_FILE = CONFIG_DIR / "printer_config.json"
|
|
|
|
DEFAULT_CONFIG = {
|
|
"label_printer": {
|
|
"ip": "192.168.9.221",
|
|
"port": 9100,
|
|
"enabled": False,
|
|
},
|
|
}
|
|
|
|
|
|
class PrintConfigManager:
|
|
"""打印机 IP/端口 配置读写"""
|
|
|
|
@staticmethod
|
|
def _ensure_file() -> None:
|
|
if not CONFIG_DIR.exists():
|
|
CONFIG_DIR.mkdir(parents=True)
|
|
if not CONFIG_FILE.exists():
|
|
PrintConfigManager.save_config(DEFAULT_CONFIG)
|
|
|
|
@staticmethod
|
|
def get_config() -> dict:
|
|
PrintConfigManager._ensure_file()
|
|
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
|
|
@staticmethod
|
|
def save_config(config: dict) -> None:
|
|
if not CONFIG_DIR.exists():
|
|
CONFIG_DIR.mkdir(parents=True)
|
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
json.dump(config, f, indent=2, ensure_ascii=False)
|
|
|
|
@staticmethod
|
|
def get_printer(name: str = "label_printer") -> dict:
|
|
config = PrintConfigManager.get_config()
|
|
return config.get(name, DEFAULT_CONFIG.get("label_printer", {}))
|