Skip to content

Instantly share code, notes, and snippets.

@tsuriga
Created March 20, 2016 13:48
Show Gist options
  • Select an option

  • Save tsuriga/5bc5bbfaf21c6a51cda7 to your computer and use it in GitHub Desktop.

Select an option

Save tsuriga/5bc5bbfaf21c6a51cda7 to your computer and use it in GitHub Desktop.

Revisions

  1. tsuriga created this gist Mar 20, 2016.
    26 changes: 26 additions & 0 deletions config.ini
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    [DEFAULT]
    ; Operation mode
    ; This is a global value for all sections
    mode = master

    [server]

    ; Connection lifetime
    timeout = 3600

    ; Garbage collection mode
    ; Accepted values: none, aggressive, smart, auto
    gc_mode = smart

    ; Notice there is no mode set under this section - it will be read from defaults


    [client]

    ; Fallback procedure for clients
    ; Accepted values: none, polling, auto
    ; Invalid value as an example here
    fallback = socket

    ; Overriding global value here
    mode = slave
    59 changes: 59 additions & 0 deletions validate.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    from configparser import ConfigParser


    class MyException(Exception):
    pass


    class MyConfig(ConfigParser):
    def __init__(self, config_file):
    super(MyConfig, self).__init__()

    self.read(config_file)
    self.validate_config()

    def validate_config(self):
    required_values = {
    'server': {
    'timeout': None,
    'gc_mode': ('none', 'aggressive', 'smart', 'auto'),
    'mode': ('master')
    },
    'client': {
    'fallback': ('none', 'polling', 'auto'),
    'mode': ('master', 'slave')
    }
    }
    """
    Notice the different mode validations for global mode setting: we can
    enforce different value sets for different sections
    """

    for section, keys in required_values.items():
    if section not in self:
    raise MyException(
    'Missing section %s in the config file' % section)

    for key, values in keys.items():
    if key not in self[section] or self[section][key] == '':
    raise MyException((
    'Missing value for %s under section %s in ' +
    'the config file') % (key, section))

    if values:
    if self[section][key] not in values:
    raise MyException((
    'Invalid value for %s under section %s in ' +
    'the config file') % (key, section))

    cfg = {}

    try:
    # The example config file has an invalid value so cfg will stay empty first
    cfg = MyConfig('config.ini')
    except MyException as e:
    # Initially you'll see this due to the invalid value
    print(e)
    else:
    # Once you fix the config file you'll see this
    print(cfg['client']['fallback'])