Oslo Config (oslo.config) 使用

安装

所有oslo_xxx包在PyPI上的名称都是oslo.xxx
安装oslo.confg

pip  install   oslo.confg

选项类型

声明选项时需要指定选项的类型,oslo.config库提供了以下常用的类型,用户也可以自定义类型

Oslo Config (oslo.config) 使用_第1张图片
图片.png

范例

olso_test.py :

# -*- coding: utf-8 -*-

import sys
from oslo_config import cfg
from oslo_config import types

# 自定义端口类型,范围在(1, 65535)
PortType = types.Integer(1, 65535)

opts = [
    cfg.StrOpt('ip',
               default='127.0.0.1',
               help='IP address to listen on.'),
    cfg.Opt('port',
            type=PortType,
            default=8080,
            help='Port number to listen on.')
]

# 注册选项
cfg.CONF.register_opts(opts)

# group database
database = cfg.OptGroup(name='database',
                      title='group database Options')
opts = [
    cfg.StrOpt('connection',
               default='',
               help='item connection in group database.')
]
cfg.CONF.register_group(database)
cfg.CONF.register_opts(opts, group=database)

# 指定配置文件
cfg.CONF(default_config_files=['config.conf'])

print('DEFAULT: ip=%s  port=%s' %(cfg.CONF.ip,cfg.CONF.port))
print('database: connection=%s' %(cfg.CONF.database.connection))

config.conf :

[DEFAULT]
ip = 8.8.8.8
port = 9090

[database]
connection = mysql+pymysql://root:[email protected]/cinder?charset=utf8

图片.png

注意: 如果多个配置文件的配置项重名,后解析的会覆盖先解析的!

cinder里使用:

        # 读取cinder.conf中配置项
        config = ConfigParser.ConfigParser()
        config.read(self.PATH_LOCAL_CINDER_CONFIG)
        if not config.has_section('backend_storage'):
            raise exception.CinderException(message='The cinder.conf file is not config the backend_storage items.')
        self.main_node_ip = config.get('backend_storage', 'main_node_ip')

参考

Openstack 之 oslo.config

你可能感兴趣的:(Oslo Config (oslo.config) 使用)