configuration.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import json
  2. from sanic.log import error_logger
  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. error_logger.error(f"config file does not exist:{e}")
  13. sys.exit()
  14. def get_config(self):
  15. """"读取配置"""
  16. return self.config
  17. # 解密密码和序列号
  18. # config['hardDiskdataBase']['password'] = DesEncrypt(
  19. # config['hardDiskdataBase']['password']).decode('utf-8')
  20. # config['code'] = DesEncrypt(config['code']).decode('utf-8')
  21. def set_config(self, **kwargs):
  22. config = self.get_config()
  23. for k, v in kwargs.items():
  24. k = k.split('.')
  25. len_k = len(k)
  26. try:
  27. if len_k == 1:
  28. config[k[0]] = v
  29. elif len_k == 2:
  30. config[k[0]][k[1]] = v
  31. elif len_k == 3:
  32. config[k[0]][k[1]][k[2]] = v
  33. except KeyError as e:
  34. print("键名错误", e)
  35. return False
  36. with open(self.path, "w") as f:
  37. json.dump(config, f)
  38. return True
  39. def add_device(self):
  40. pass
  41. def delete_device(self):
  42. pass
  43. def updata_device(self):
  44. pass
  45. if __name__ == '__main__':
  46. # config = Configuration("./config.json")
  47. # dict = {"hardDiskdataBase.username": "zz", "hardDiskdataBase.ip": "127.0.0.1"}
  48. # config.set_config(**dict)
  49. config = Configuration()
  50. res = config.set_config(**{"activation_code": "local_code"})
  51. print(res)