configuration.py 1.8 KB

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