在 Python 中设置配置文件的最佳方法是什么

Kee*_*ett 5 python configuration json yaml

我意识到之前有人问过这个问题(在 Python 中使用设置文件的最佳实践是什么?)但是看到 7 年前有人问过这个问题,我觉得有必要再次讨论一下技术是如何发展的。

我有一个 python 项目,需要根据环境变量的值使用不同的配置。由于使用环境变量来选择配置文件很简单,我的问题如下:

当基于环境需要多个配置时,在python中设置配置文件的最佳实践是什么格式?

我意识到 python 带有一个 ConfigParser 模块,但我想知道使用 YAML 或 JSON 等格式是否更好,因为它们易于跨语言使用而越来越受欢迎。当您有多个配置时,哪种格式更容易维护?

小智 6

这实在是太晚了,但这就是我所使用的,并且我对它很满意(如果您愿意接受纯 Python 解决方案)。我喜欢它,因为我的配置可以根据使用环境变量的部署位置自动设置。我使用它的时间不长,所以如果有人发现问题,我会洗耳恭听。

结构:

|--settings
   |--__init__.py
   |--config.py
Run Code Online (Sandbox Code Playgroud)

配置文件

class Common(object):
    XYZ_API_KEY = 'AJSKDF234328942FJKDJ32'
    XYZ_API_SECRET = 'KDJFKJ234df234fFW3424@#ewrFEWF'

class Local(Common):
    DB_URI = 'local/db/uri'
    DEBUG = True

class Production(Common):
    DB_URI = 'remote/db/uri'
    DEBUG = False

class Staging(Production):
    DEBUG = True
Run Code Online (Sandbox Code Playgroud)

__init__.py

from settings.config import Local, Production, Staging
import os

config_space = os.getenv('CONFIG_SPACE', None)
if config_space:
    if config_space == 'LOCAL':
        auto_config = Local
    elif config_space == 'STAGING':
        auto_config = Staging
    elif config_space == 'PRODUCTION':
        auto_config = Production
    else:
        auto_config = None
        raise EnvironmentError(f'CONFIG_SPACE is unexpected value: {config_space}')
else:
    raise EnvironmentError('CONFIG_SPACE environment variable is not set!')
Run Code Online (Sandbox Code Playgroud)

如果我的环境变量在我的应用程序所在的每个位置都设置了,我可以根据需要将其带入我的模块中:

from settings import auto_config as cfg
Run Code Online (Sandbox Code Playgroud)


小智 3

如果您确实想使用基于环境的 YAML 配置,您可以这样做:

配置文件

import yaml
import os

config = None

filename = os.getenv('env', 'default').lower()
script_dir = os.path.dirname(__file__)
abs_file_path = os.path.join(script_dir, filename)
with open(abs_file_path, 'r') as stream:
    try:
        config = yaml.load(stream)
    except yaml.YAMLError as exc:
        print(exc)
Run Code Online (Sandbox Code Playgroud)