zoukankan      html  css  js  c++  java
  • oslo.config

    5.1 cfg Module--可以用来通过命令行或者是配置文件来配置一些options:
    example1:
    #!/usr/bin/env python
    # encoding: utf-8

    from oslo_config import cfg
    from oslo_config import types

    # 定义了一个类型和范围
    PortType = types.Integer(1,65535)

    # 定义一组选项
    common_opts = [
        #定义了一个Str类型的选项,名字是bind_host,默认值是0.0.0.0,还有帮助信息
        #用的是Opt的子类来定义的,所以无需指定类类型,因为类型已经定下来了就是Str类型
    cfg.StrOpt('bind_host',default='0.0.0.0',
    help='IP address to listen on.'),
    #使用Opt类来定义一个选项,因为用的是基类,类型可以是任意的,所以需要使用type字段明确其类型
    #使用这种方式的好处我觉得就是可以定制类型的值范围
    cfg.Opt('bind_port',
    type=PortType,
    default=9292,
    help="Port number to listen on.")

    Opt是父类,其下有很多特定类型的子类。下面是cfg Module支持的一些类型
    oslo_config.types.String 字符串
    oslo_config.types.Boolean 布尔类型
    oslo_config.types.Integer 整数
    oslo_config.types.Float 浮点
    oslo_config.types.List 列表
    oslo_config.types.Dict 字典
    oslo_config.types.IPAddress IP地址

    对应
    oslo_config.cfg.StrOpt
    oslo_config.cfg.BoolOpt
    oslo_config.cfg.IntOpt
    oslo_config.cfg.PortOpt
    oslo_config.cfg.FloatOpt
    oslo_config.cfg.ListOpt
    oslo_config.cfg.DictOpt
    oslo_config.cfg.IPOpt

    example2:
    #!/usr/bin/env python
    # encoding: utf-8

    from oslo_config import cfg
    from oslo_config import types

    DEFAULT_EXTENSIONS = [
    'nova.api.openstack.compute.contrib.standard_extensions'
    ]

    # cfg.MultiOpt的子类用来定义一个多值的选项,值的类型是str
    osapi_compute_extension_opt = cfg.MultiStrOpt('osapi_compute_extension',default=DEFAULT_EXTENSIONS)

    5.2 Registering Options--如何去注册选项和使用选项
    example3:
    #!/usr/bin/env python
    # encoding: utf-8

    from oslo_config import cfg
    from oslo_config import types

    PortType = types.Integer(1, 65535)
    #定义一组选项
    common_opts = [
    cfg.StrOpt('bind_host',
    default='0.0.0.0',
    help='IP address to listen on.'),
    cfg.Opt('bind_port',
    type=PortType,
    default=9292,
    help='Port number to listen on.')
    ]
    #注册选项
    def add_common_opts(conf):
    conf.register_opts(common_opts)
    #使用选项
    def get_bind_host(conf):
    return conf.bind_host

    def get_bind_port(conf):
    return conf.bind_port

    #创建配置类
    cf = cfg.CONF
    #开始注册
    add_common_opts(cf)
    print(get_bind_host(cf))


    5.3 命令行配置
    import sys
    from oslo_config import cfg
    from oslo_config import types
    cli_opts = [
    cfg.BoolOpt('verbose',
    short='v',
    default=False,
    help='Print more verbose output.'),
    cfg.BoolOpt('debug',
    short='d',
    default=False,
    help='Print debugging output.'),
    ]

    def add_common_opts(conf):
    conf.register_cli_opts(cli_opts)

    cf = cfg.CONF
    add_common_opts(cf);
    cf(sys.argv[1:]) #将命令行参数传递给CONF类,argv[0]是程序名,所以从1开始

    if cf.debug:
    print("开启调试")
    else:
    print("关闭调试")

    >>> sys可以在命令行操作开启调试
    python test.py --debug

    因此,可以写conf文件直接使用config-file修改配置
    python example4.py --config-file=example4.conf

    5.4 option Groups--配置组
    #!/usr/bin/env python
    # encoding: utf-8
    #定义了一个名为rabbit的组,记住组的名字也很重要,后面会用到
    rabbit_group = cfg.OptGroup(name='rabbit',
    title='RabbitMQ options')

    #定义了两个选项,和上文中说到的定义选项没有任何区别
    rabbit_host_opt = cfg.StrOpt('host',
    default='localhost',
    help='IP/hostname to listen on.'),
    rabbit_port_opt = cfg.PortOpt('port',
    default=5672,
    help='Port number to listen on.')
    def register_rabbit_opts(conf):
        #通过CONF类来注册了一个组,(CONF类啥都要先注册后使用,注册其实就是在CONF类内部做解析呢)
    conf.register_group(rabbit_group)
    # options can be registered under a group in either of these ways:
    #注册选项的时候通过指定组来把选项添加到特定的组中,指定组可以有如下两种方式,一种就是直接使用OptGroup实例的方式
    #另外一种就是使用配置组的名字这里是rabbit
    conf.register_opt(rabbit_host_opt, group=rabbit_group)
    conf.register_opt(rabbit_port_opt, group='rabbit')
    #没提供group就是默认组DEFAULT

    之前只有默认组的时候,在命令行使用–debug就会自动去DEFAULT组去找,那么现在添加了一个rabbit组,如果要找rabbit组中的host该怎么通过命令行来指定呢这也是很方便的直接通过前缀来判断例如–rabbit-host指的就是rabbit组中的host选项。配置文件句不多说了,定义一个[rabbit]就可以了,如何在代码中访问呢,也很简单,直接使用conf.rabbit.host就可以了。


    5.5 代码运行
    def start():
    add_register()
    #配置文件路径['glance-api.conf']绝对相对都可以.一般这样用CONF(sys.argv[1:] --config-dir
    CONF(default_config_files=['glance-api.conf'])
    #CONF(sys.argv[1:])

    if __name__ == '__main__':
    #
    CONF = cfg.CONF
    start()
    print(CONF.bind_port,CONF.bind_host,CONF.keystone_authtoken.auth_uri)


    5.6 即写一个配置文件.conf,写一个脚本文件.py,可以通过py运行conf.
    脚本文件包括常见配置和配置组,然后进行注册和debug.


    综合性实例:
    app.py和app.conf
    # app.conf
    [simple]

    enable = True

    [morestuff]

    #StrOpt
    message = Hello World

    # ListOpt
    usernames = ['Joe', 'Jessica', 'Peter']

    # DictOpt
    jobtitles = {'Joe': 'Manager', 'Jessica': 'CEO', 'Peter': 'Security Guard'}

    # InOpt
    payday = 20

    # FloatOpt
    pi = 3.14

    # app.py
    # -*- coding: utf-8 -*-
    from __future__ import print_function
    from oslo_config import cfg

    opt_simple_group = cfg.OptGroup(name='simple', title='A Simple Example')

    opt_morestuff_group = cfg.OptGroup(name='morestuff', title='A More Complex Example')

    simple_opts = [cfg.BoolOpt('enable', default=False, help=('True enables,False disables'))]

    morestuff_opts = [cfg.StrOpt('message', default='Nodata', help=('A message')),

    cfg.ListOpt('usernames', default=None, help=('A list of usernames')),

    cfg.DictOpt('jobtitles', default=None, help=('A dictionary of usernames and job titles')),

    cfg.IntOpt('payday', default=30, help=('Default payday monthly date')),

    cfg.FloatOpt('pi', default=0.0, help=('The value of Pi'))

    ]

    CONF = cfg.CONF

    CONF.register_group(opt_simple_group)

    CONF.register_opts(simple_opts, opt_simple_group)

    CONF.register_group(opt_morestuff_group)

    CONF.register_opts(morestuff_opts, opt_morestuff_group)

    if __name__ == '__main__':
    CONF(default_config_files=['app.conf'])
    print('(simple) enable: {}'.format(CONF.simple.enable))
    print('(morestuff) message:{}'.format(CONF.morestuff.message))
    print('(morestuff)usernames: {} '.format(CONF.morestuff.usernames))
    print('(morestuff) jobtitles: {}'.format(CONF.morestuff.jobtitles))
    print('(morestuff) payday: {} '.format(CONF.morestuff.payday))
    print('(morestuff)pi: {}'.format(CONF.morestuff.pi))

    >>>
    (simple) enable: True
    (morestuff) message:Hello World
    (morestuff)usernames: ["['Joe'", "'Jessica'", "'Peter']"]
    (morestuff) jobtitles: {"{'Joe'": "'Manager'", "'Peter'": "'Security Guard'}", "'Jessica'": "'CEO'"}
    (morestuff) payday: 20
    (morestuff)pi: 3.14

  • 相关阅读:
    记录JavaScript的util.js类库
    Shiro登录中遇到了问题
    【转载】JavaScript导出Excel
    react-router
    react 表单
    html5定位getLocation()
    html5存储方式localstorage和sessionStorage
    position导致Safari工具栏不自动隐藏
    input type="datetime-local" 时placeholder不显示
    vuex(1.0版本写法)
  • 原文地址:https://www.cnblogs.com/giotto95827/p/8761091.html
Copyright © 2011-2022 走看看