Oslo is a set of python libraries and used in OpenStack as a common library. Oslo shows its importance as it provides a common library for developers in other services in OpenStack. Before Oslo implementation, the OpenStack projects share the source codes by copying from repositories. In this post, we are going to test the basic usage of oslo.config library – a library for parsing configuration from config file and command line.

I am going to test oslo.config in virtualenv in order to avoid the affects to my host OS (ubuntu 12.04). I install oslo.config and create 2 files – test.conf and test.py.

$ pip install oslo.config

$ touch test.conf

$ touch test.py

First, write some settings for test.conf:

[test]

enable = True

usr_name = 'VietStack'

hobby = ['Football', 'Guitar', 'OpenStack']

friend = {'Maria': 6996, 'Jackie Chan': 60}

age = 20

Let's take a look to the code of test.py:

 

from oslo.config import cfg
opt_group = cfg.OptGroup(name='test',
                         title='An example of Test'
                         )
test_opts = [
 cfg.BoolOpt('enable',
              default=False,
             ),
 cfg.StrOpt('usr_name',
              default='No Name',
              help=('Name of user')),
 cfg.ListOpt('hobby',
              default=None,
              help=('List of hobby')),
 cfg.DictOpt('friend',
              default=None,
              help=('List of friends')),
 cfg.IntOpt('age',
             default=69,
             help=('Age'))
]
def parser(conf):
 CONF = cfg.CONF
 CONF.register_group(opt_group)
 CONF.register_opts(test_opts, opt_group)
 CONF(default_config_files=conf)
 return CONF
if __name__ == "__main__":
 CONF=parser(['test.conf'])
 print(CONF.test.enable)
 print(CONF.test.hobby)
 print(CONF.test.friend)
 print(CONF.test.age)
 print(CONF.test.usr_name)

Meanings of terms used by oslo.config:

opt_group: Variable that holds the “test” group in test.conf

test_opts: Variable that holds the options in the “test” group in test.conf

Then, we register the group and group options:

CONF.register_group(opt_group)

CONF.register_opts(test_opts, opt_group)

Using the config file:

CONF(default_config_files=conf)

Runs the test.py then magic will happen!

NOTE:

1. In this example, I only provide the relative path “CONF=parser(['test.conf'])”. You should provide the absolute path of test.conf to ensure the stability of the file.

2. There are many types of options in oslo.config such as: MultiStrOpt, FloatOpt, etc.

 

2015/06/30

VietStack Team