简体   繁体   中英

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. I suggest you write a class that provides a wrapper around a raw 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. 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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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