使用aumbry支持加密和非加密配置

Jav*_*ock 7 python configuration python-cryptography aumbry

我们有一个加载Python应用程序config.ymlaumbry.出于生产目的,我们需要使用fernet加密此配置,aumbry可以无缝加载.

我们希望能够以透明方式加载未加密和加密,例如,如果找到则加载未加密,如果没有(生产)加载加密.到目前为止,我们已经实现了

加密

import cryptography.Fernet as fn
from os.path import split, splitext

def _encrypt_file(path, key):
    with open(path, 'rb') as infile:
        file_data = infile.read()
        nc_data= fn(key).encrypt(file_data)
        infile.close()

        base_path, filename = split(path)
        name, _ = splitext(filename)
        nc_name = "{}.{}".format(name, 'nc')
        with open(join(base_path, nc_name), 'wb') as outfile:
            outfile.write(nc_data)
            outfile.close()
Run Code Online (Sandbox Code Playgroud)

Aumbry配置

from aumbry.errors import LoadError

def _get_configuration():
    return aumbry.load(
        aumbry.FILE,
        AppConfig,
        options={
            'CONFIG_FILE_PATH': "config.yml"            
        }
    )

def _get_encrypted_configuration():
    return aumbry.load(
        aumbry.FERNET,
        AppConfig,
        options={
            'CONFIG_FILE_PATH': "config.nc",
            'CONFIG_FILE_FERNET_KEY': 'bZhF6nN4A6fhVBPtru2dG1_6d7i0d_B2FxmsybjtE-g='
        }
    )
def load_config():
    """General method to load configuration"""
    try:
        return _get_configuration()
    except LoadError:
        try: 
            return _get_encrypted_configuration()
        except LoadError:
            return None
Run Code Online (Sandbox Code Playgroud)
  • 是否有更优雅的方式来实现这种行为?

Jam*_*Lim 3

根据构建 Python 应用程序的框架,通常可以使用某种全局“模式”值。

例如,Flask 使用FLASK_ENV可以设置为 或 的环境development变量production。在应用程序内,您可以使用

app.config['DEBUG']  # True if FLASK_ENV is "development"
Run Code Online (Sandbox Code Playgroud)

来区分这两种模式。

在您的情况下,可以重构 ambury 加载器来执行以下操作:

config_loader_cls = EncryptedConfigLoader if environment=='production' else PlainConfigLoader
Run Code Online (Sandbox Code Playgroud)

EncryptedConfigLoader如果配置没有加密以获得额外的安全性,我会更进一步并且失败。