增加切换账号功能
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -12,18 +13,52 @@ class IOSAIStorage:
|
||||
iosai_dir.mkdir(parents=True, exist_ok=True)
|
||||
return iosai_dir
|
||||
|
||||
# @classmethod
|
||||
# def save(cls, data: dict | list, filename: str = "data.json") -> Path:
|
||||
# """
|
||||
# 存储数据到 C:/Users/<用户名>/IOSAI/filename
|
||||
# """
|
||||
# file_path = cls._get_iosai_dir() / filename
|
||||
# try:
|
||||
# with open(file_path, "w", encoding="utf-8") as f:
|
||||
# json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
# print(f"[IOSAIStorage] 已保存到: {file_path}")
|
||||
# except Exception as e:
|
||||
# print(f"[IOSAIStorage] 写入失败: {e}")
|
||||
# return file_path
|
||||
|
||||
@classmethod
|
||||
def save(cls, data: dict | list, filename: str = "data.json") -> Path:
|
||||
"""
|
||||
存储数据到 C:/Users/<用户名>/IOSAI/filename
|
||||
"""
|
||||
def save(cls, data: dict | list, filename: str = "data.json", mode: str = "overwrite") -> Path:
|
||||
file_path = cls._get_iosai_dir() / filename
|
||||
try:
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
print(f"[IOSAIStorage] 已保存到: {file_path}")
|
||||
except Exception as e:
|
||||
print(f"[IOSAIStorage] 写入失败: {e}")
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _load_json():
|
||||
try:
|
||||
return json.loads(file_path.read_text("utf-8"))
|
||||
except Exception:
|
||||
return {} if isinstance(data, dict) else []
|
||||
|
||||
if mode == "merge" and isinstance(data, dict):
|
||||
old = _load_json()
|
||||
if not isinstance(old, dict):
|
||||
old = {}
|
||||
old.update(data)
|
||||
to_write = old
|
||||
elif mode == "append" and isinstance(data, list):
|
||||
old = _load_json()
|
||||
if not isinstance(old, list):
|
||||
old = []
|
||||
old.extend(data)
|
||||
to_write = old
|
||||
else:
|
||||
to_write = data # 覆盖
|
||||
|
||||
# 原子写入
|
||||
tmp = file_path.with_suffix(file_path.suffix + ".tmp")
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(to_write, f, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, file_path)
|
||||
print(f"[IOSAIStorage] 已写入: {file_path}")
|
||||
return file_path
|
||||
|
||||
@classmethod
|
||||
|
||||
Reference in New Issue
Block a user