Ejemplo n.º 1
0
def load_config():
    """
    載入設定檔
    """
    cfg_path = os.path.expanduser(r'~\.skcom\skcom.yaml')
    enc_path = cfg_path + '.enc'
    config = None
    load_plain = False
    logger = logging.getLogger('helper')
    message = ''

    # 嘗試讀取加密設定
    try:
        with open(enc_path, 'rb') as enc_file:
            secret = enc_file.read()
            password = getpass('請輸入設定檔密碼: ')
            plain = decrypt_text(secret, password)
            config = yaml.load(plain, Loader=yaml.SafeLoader)
        logger.info('已載入加密設定')
        logger.info('如果需要變更設定檔, 執行下列指令可以解密:')
        logger.info('  python -m skcom.tools.cfdec')
    except FileNotFoundError as ex:
        load_plain = True
    except Exception as ex:
        # TODO: 這裡掛掉的可能性很多種, 有改善空間
        message = str(ex)

    # 嘗試讀取明文設定
    if load_plain:
        try:
            with open(cfg_path, 'r', encoding='utf-8') as cfg_file:
                config = yaml.load(cfg_file, Loader=yaml.SafeLoader)
            logger.warning('目前設定檔沒有加密, 建議您加密避免帳號外流')
            logger.warning('執行下列指令即可加密:')
            logger.warning('  python -m skcom.tools.cfenc')
        except FileNotFoundError as ex:
            # 複製設定檔模板
            tpl_path = os.path.dirname(
                os.path.realpath(__file__)) + r'\conf\skcom.yaml'
            shutil.copy(tpl_path, cfg_path)
            with open(cfg_path, 'r', encoding='utf-8') as cfg_file:
                config = yaml.load(cfg_file, Loader=yaml.SafeLoader)
        except Exception as ex:
            message = str(ex)

    if config is not None:
        # 檢查設定檔是不是沒改過的模板
        if config['account'] == 'A123456789':
            logger.warning('請開啟設定檔, 將帳號密碼改為您的證券帳號')
            logger.warning('設定檔路徑: %s', cfg_path)
            raise ConfigException('設定檔尚未修改', loaded=True)
    else:
        # 檢查設定檔是否載入失敗
        raise ConfigException('設定檔讀取失敗:\n%s' % message)

    # TODO: 如果 BusmHandler 的程式配置實作完成, 可能就不需要用重新載入的設計
    # reset_logging(config)

    return config
Ejemplo n.º 2
0
def main():
    logger = logging.getLogger('helper')
    cfg_path = os.path.expanduser(r'~\.skcom\skcom.yaml')

    try:
        # 解密
        with open(cfg_path + '.enc', 'rb') as enc_file:
            secret = enc_file.read()
            password = getpass('請輸入設定檔密碼: ')
            plain = decrypt_text(secret, password)

        # 儲存明文設定檔, 刪除加密設定檔
        with open(cfg_path, 'w', encoding='utf-8') as cfg_file:
            cfg_file.write(plain)
            os.remove(cfg_path + '.enc')

        logger.info('解密完成')
    except Exception as ex:
        logger.error(ex)