# -*- coding: utf-8 -*- # @Time : 2021/02/22 # @Author : ricky # @File : configini.py # @Software: vscode """ 系统配置类 """ import configparser import os from utils import globalvalues from utils import aescrypt class Config: """ 系统配置类 """ # 敏感属性 __SENSITIVE_TUPLE = ('password', 'pass', 'pwd') def __init__(self, filepath=None): if filepath: config_path = filepath else: config_path = os.path.join(os.path.abspath('.'), 'config.ini') if len(globalvalues.CONFIG_INI_PATH) == 0: globalvalues.CONFIG_INI_PATH = config_path self.config_parser = configparser.ConfigParser() if not os.path.exists(globalvalues.CONFIG_INI_PATH): self.config_parser['config'] = {'enable': False} self.write() self.config_parser.read(globalvalues.CONFIG_INI_PATH) self.crypt = aescrypt.AesCrypt() def get_value(self, section, key): """ 根据section和key获取value 参数: section: 节点 key: 键 返回: value: 值 """ if not self.config_parser.has_section(section): return '' value = self.config_parser.get(section, key) if key in self.__SENSITIVE_TUPLE: value = self.crypt.decrypt(value) return value def get_dict(self): """ 获取配置字典 返回: 字典类型数据 """ d = {} sections = self.config_parser.sections() for s in sections: items = self.config_parser.items(s) for item in items: k = item[0] v = item[1] if k in self.__SENSITIVE_TUPLE: v = self.crypt.decrypt(v) d[s + '.' + k] = v return d def set_value(self, section, key, value): """ 根据section和key设置value 参数: section: 节点 key: 键 value: 值 """ if not self.config_parser.has_section(section): self.config_parser.add_section(section) if key in self.__SENSITIVE_TUPLE: value = self.crypt.encrypt(value).replace('\n','') self.config_parser.set(section, key, value) def write(self): """写入配置文件""" with open(globalvalues.CONFIG_INI_PATH, 'w+') as config_file: self.config_parser.write(config_file)