configini.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2021/02/22
  3. # @Author : ricky
  4. # @File : configini.py
  5. # @Software: vscode
  6. """
  7. 系统配置类
  8. """
  9. import configparser
  10. import os
  11. from utils import globalvalues
  12. from utils import aescrypt
  13. class Config:
  14. """
  15. 系统配置类
  16. """
  17. # 敏感属性
  18. __SENSITIVE_TUPLE = ('password', 'pass', 'pwd')
  19. def __init__(self, filepath=None):
  20. if filepath:
  21. config_path = filepath
  22. else:
  23. config_path = os.path.join(os.path.abspath('.'), 'config.ini')
  24. if len(globalvalues.CONFIG_INI_PATH) == 0:
  25. globalvalues.CONFIG_INI_PATH = config_path
  26. self.config_parser = configparser.ConfigParser()
  27. if not os.path.exists(globalvalues.CONFIG_INI_PATH):
  28. self.config_parser['config'] = {'enable': False}
  29. self.write()
  30. self.config_parser.read(globalvalues.CONFIG_INI_PATH)
  31. self.crypt = aescrypt.AesCrypt()
  32. def get_value(self, section, key):
  33. """
  34. 根据section和key获取value
  35. 参数:
  36. section: 节点
  37. key: 键
  38. 返回:
  39. value: 值
  40. """
  41. if not self.config_parser.has_section(section):
  42. return ''
  43. value = self.config_parser.get(section, key)
  44. if key in self.__SENSITIVE_TUPLE:
  45. value = self.crypt.decrypt(value)
  46. return value
  47. def get_dict(self):
  48. """
  49. 获取配置字典
  50. 返回:
  51. 字典类型数据
  52. """
  53. d = {}
  54. sections = self.config_parser.sections()
  55. for s in sections:
  56. items = self.config_parser.items(s)
  57. for item in items:
  58. k = item[0]
  59. v = item[1]
  60. if k in self.__SENSITIVE_TUPLE:
  61. v = self.crypt.decrypt(v)
  62. d[s + '.' + k] = v
  63. return d
  64. def set_value(self, section, key, value):
  65. """
  66. 根据section和key设置value
  67. 参数:
  68. section: 节点
  69. key: 键
  70. value: 值
  71. """
  72. if not self.config_parser.has_section(section):
  73. self.config_parser.add_section(section)
  74. if key in self.__SENSITIVE_TUPLE:
  75. value = self.crypt.encrypt(value).replace('\n','')
  76. self.config_parser.set(section, key, value)
  77. def write(self):
  78. """写入配置文件"""
  79. with open(globalvalues.CONFIG_INI_PATH, 'w+') as config_file:
  80. self.config_parser.write(config_file)