简体   繁体   English

使用 configparser 为多个环境配置

[英]Config for multiple environments wth configparser

This might be a long question but please bear with me.这可能是一个很长的问题,但请多多包涵。

I frequently create small automation programs that I test in dev environments and then promote to work in production.我经常创建小型自动化程序,我在开发环境中进行测试,然后推广到生产环境中工作。 I use config files to store all my config and it's worked pretty well for me so far but the one thing that makes it a bit harder to work with is switching values based on environments.我使用配置文件来存储我的所有配置,到目前为止它对我来说效果很好,但是让它更难使用的一件事是根据环境切换值。

I have used something like the following structure in the past but have been wondering if there's a better way to maintain the config files.我过去使用过类似以下结构的东西,但一直想知道是否有更好的方法来维护配置文件。

[Global]
.
.
Environment = Dev

[SpecificSection-Dev]
key1 = dev value1
key2 = dev value2
keyn = dev valuen


[SpecificSection-Prod]
key1 = prod value1
key2 = prod value2
keyn = prod valuen

I would then read the config file and use the environment decide what gets picked with something like the following:然后我会读取配置文件并使用环境来决定选择什么,如下所示:

parser.get('SpecificSection-' + parser.get('Global','Environment'), 'key1')

In previous versions of my code, I have commented out values of other environments and I manually comment and uncomment the values I need for the task at hand.在我以前的代码版本中,我已经注释掉了其他环境的值,并且我手动注释和取消注释我手头任务所需的值。

My question is simply, is there a better way of doing this?我的问题很简单,有没有更好的方法来做到这一点? Ideally, I would like to define the environment once in the config file and not have to handle it in the code explicitly like I do.理想情况下,我想在配置文件中定义一次环境,而不必像我一样在代码中明确处理它。

Thanks, Karan谢谢, 卡兰

I am not very familiar with Python, so I will use a Java-like pseudocode rather than attempt to write Python code in this answer.我对 Python 不是很熟悉,所以我将使用类似 Java 的伪代码,而不是尝试在这个答案中编写 Python 代码。 I suggest you write a class that provides a wrapper around a raw parser object.我建议您编写一个 class,它为原始parser object 提供一个包装器。 The implementation of the get() operation of the wrapper class can delegate to the parser object like you have shown in your question.包装器 class 的get()操作的实现可以委托给parser object ,就像您在问题中显示的那样。 So, this will look something like (pseudocode):所以,这看起来像(伪代码):

class ParserWrapper {
  Parser   parser;
  String   env;

  ParserWrapper(String file) {
    parser = new Parser(file);
    env = parser.get("Global", "Environment");
  }

  String get(String name) {
    return parser.get("SpecificSection-" + env, name)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM