util.py 999 B

123456789101112131415161718192021222324252627282930313233343536
  1. import json
  2. import os
  3. from typing import Any
  4. from config.settings import USER_SETTING_PATH
  5. def update_user_setting(field_name: str, new_value: Any) -> bool:
  6. """
  7. 修改 json 文件中指定字段的值
  8. :param field_name: 要修改的字段名
  9. :param new_value: 新值
  10. :return: 执行成功返回 True,失败返回 False
  11. """
  12. try:
  13. with open(USER_SETTING_PATH, "r", encoding="utf-8") as f:
  14. data = json.load(f)
  15. data[field_name] = new_value
  16. with open(USER_SETTING_PATH, "w", encoding="utf-8") as f:
  17. json.dump(data, f, ensure_ascii=False, indent=2)
  18. return True
  19. except Exception as e:
  20. print(f"修改失败:{e}")
  21. return False
  22. def get_user_setting(field_name: str) -> Any:
  23. """读取指定字段值"""
  24. if not os.path.exists(USER_SETTING_PATH):
  25. return None
  26. with open(USER_SETTING_PATH, "r", encoding="utf-8") as f:
  27. data = json.load(f)
  28. return data.get(field_name)