configuration.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import json
  2. import os
  3. import sys
  4. from AES_crypt import decrypt
  5. class Configuration:
  6. def __init__(self, path='config.json'):
  7. self.path = path
  8. try:
  9. with open(self.path) as json_file:
  10. self.config = json.load(json_file)
  11. except FileNotFoundError as e:
  12. print(f"当前路径:{os.getcwd()}无法找到配置文件:{e}")
  13. input("按任意键退出!")
  14. sys.exit()
  15. def get_config(self):
  16. """"读取配置"""
  17. return self.config
  18. # 解密密码和序列号
  19. # config['hardDiskdataBase']['password'] = DesEncrypt(
  20. # config['hardDiskdataBase']['password']).decode('utf-8')
  21. # config['code'] = DesEncrypt(config['code']).decode('utf-8')
  22. def set_config(self, **kwargs):
  23. config = self.get_config()
  24. for k, v in kwargs.items():
  25. k = k.split('.')
  26. len_k = len(k)
  27. try:
  28. if len_k == 1:
  29. config[k[0]] = v
  30. elif len_k == 2:
  31. config[k[0]][k[1]] = v
  32. elif len_k == 3:
  33. config[k[0]][k[1]][k[2]] = v
  34. except KeyError as e:
  35. print("键名错误", e)
  36. return False
  37. with open(self.path, "w") as f:
  38. json.dump(config, f)
  39. return True
  40. def add_device(self):
  41. pass
  42. def delete_device(self):
  43. pass
  44. def updata_device(self):
  45. pass
  46. if __name__ == '__main__':
  47. # config = Configuration("./config.json")
  48. # dict = {"hardDiskdataBase.username": "zz", "hardDiskdataBase.ip": "127.0.0.1"}
  49. # config.set_config(**dict)
  50. config = Configuration()
  51. res = config.set_config(**{"activation_code": "local_code"})
  52. print(res)