| 1 |
=========== |
| 2 |
LAZR config |
| 3 |
=========== |
| 4 |
|
| 5 |
The LAZR config system is typically used to manage process configuration. |
| 6 |
Process configuration is for saying how things change when we run systems on |
| 7 |
different machines, or under different circumstances. |
| 8 |
|
| 9 |
This system uses ini-like file format of section, keys, and values. The |
| 10 |
config file supports inheritance to minimize duplication of information across |
| 11 |
files. The format supports schema validation. |
| 12 |
|
| 13 |
|
| 14 |
ConfigSchema |
| 15 |
============ |
| 16 |
|
| 17 |
A schema is loaded by instantiating the ConfigSchema class with the path to a |
| 18 |
configuration file. The schema is explicitly derived from the information in |
| 19 |
the configuration file. |
| 20 |
|
| 21 |
>>> import importlib.util |
| 22 |
>>> from pathlib import Path |
| 23 |
>>> _spec = importlib.util.find_spec('lazr.config.tests.testdata') |
| 24 |
>>> raw_schema = (Path(_spec.origin).parent / 'base.conf').read_bytes() |
| 25 |
|
| 26 |
The config file contains sections enclosed in square brackets |
| 27 |
(e.g. ``[section]``). The section name may be divided into major and minor |
| 28 |
categories using a dot (``.``). Beneath each section is a list of key-value |
| 29 |
pairs, separated by a colon (``:``). |
| 30 |
|
| 31 |
Multiple sections with the same major category may have their keys defined in |
| 32 |
another section that appends the ``.template`` suffix to the category name. |
| 33 |
|
| 34 |
A section with ``.optional`` suffix is not required. Lines that start with a |
| 35 |
hash (``#``) are comments. |
| 36 |
|
| 37 |
>>> raw_schema = (Path(_spec.origin).parent / 'base.conf').read_bytes() |
| 38 |
>>> print(raw_schema.decode('utf-8')) |
| 39 |
# This section defines required keys and default values. |
| 40 |
[section_1] |
| 41 |
key1: foo |
| 42 |
key2: bar and baz |
| 43 |
key3: Launchpad rocks |
| 44 |
key4: Fc;k yeah! |
| 45 |
key5: |
| 46 |
# This section is required, and it defines all the keys for its category. |
| 47 |
[section-2.app-b] |
| 48 |
key1: True |
| 49 |
# This section is optional; it uses the keys defined |
| 50 |
# by section_3.template. |
| 51 |
[section_3.app_a.optional] |
| 52 |
# This is a required section whose keys are defined by section_3.template |
| 53 |
# and it defines a new key. |
| 54 |
[section_3.app_b] |
| 55 |
key2: changed |
| 56 |
key3: unique |
| 57 |
# These sections define a common set of required keys and default values. |
| 58 |
[section_3.template] |
| 59 |
key1: 17 |
| 60 |
key2: 3.1415 |
| 61 |
# This section is optional. |
| 62 |
[section-5.optional] |
| 63 |
key1: something |
| 64 |
# This section has a name similar to a category. |
| 65 |
[section_33] |
| 66 |
key1: fnord |
| 67 |
key2: multiline value 1 |
| 68 |
multiline value 2 |
| 69 |
|
| 70 |
To create the schema, provide a file name. |
| 71 |
|
| 72 |
>>> from lazr.config import ConfigSchema |
| 73 |
>>> from lazr.config.interfaces import IConfigSchema |
| 74 |
>>> from zope.interface.verify import verifyObject |
| 75 |
>>> base_conf = str(Path(_spec.origin).parent / 'base.conf') |
| 76 |
>>> schema = ConfigSchema(base_conf) |
| 77 |
>>> verifyObject(IConfigSchema, schema) |
| 78 |
True |
| 79 |
|
| 80 |
The schema has a name and a file name. |
| 81 |
|
| 82 |
>>> print(schema.name) |
| 83 |
base.conf |
| 84 |
>>> print('file:', schema.filename) |
| 85 |
file: ...lazr/config/tests/testdata/base.conf |
| 86 |
|
| 87 |
If you provide an optional file-like object as a second argument to the |
| 88 |
constructor, that is used instead of opening the named file implicitly. |
| 89 |
|
| 90 |
>>> with open(base_conf, 'r') as file_object: |
| 91 |
... other_schema = ConfigSchema('/does/not/exist.conf', file_object) |
| 92 |
>>> verifyObject(IConfigSchema, other_schema) |
| 93 |
True |
| 94 |
|
| 95 |
For such schemas, the file name is taken from the first argument. |
| 96 |
|
| 97 |
>>> print(other_schema.name) |
| 98 |
exist.conf |
| 99 |
>>> print(other_schema.filename) |
| 100 |
/does/not/exist.conf |
| 101 |
|
| 102 |
A schema is made up of multiple SchemaSections. They can be iterated |
| 103 |
over in a loop as needed. |
| 104 |
|
| 105 |
>>> from operator import attrgetter |
| 106 |
>>> for section_schema in sorted(schema, key=attrgetter('name')): |
| 107 |
... print(section_schema.name) |
| 108 |
section-2.app-b |
| 109 |
section-5 |
| 110 |
section_1 |
| 111 |
section_3.app_a |
| 112 |
section_3.app_b |
| 113 |
section_33 |
| 114 |
|
| 115 |
>>> for section_schema in sorted(other_schema, key=attrgetter('name')): |
| 116 |
... print(section_schema.name) |
| 117 |
section-2.app-b |
| 118 |
section-5 |
| 119 |
section_1 |
| 120 |
section_3.app_a |
| 121 |
section_3.app_b |
| 122 |
section_33 |
| 123 |
|
| 124 |
You can check if the schema contains a section name, and that can be |
| 125 |
used to access the SchemaSection as a subscript. |
| 126 |
|
| 127 |
>>> 'section_1' in schema |
| 128 |
True |
| 129 |
>>> 'section-4' in schema |
| 130 |
False |
| 131 |
|
| 132 |
A SectionSchema can be retrieved from the schema using the ``[]`` operator. |
| 133 |
|
| 134 |
>>> section_schema_1 = schema['section_1'] |
| 135 |
>>> print(section_schema_1.name) |
| 136 |
section_1 |
| 137 |
|
| 138 |
Processes often require resources like databases or virtual hosts that have a |
| 139 |
common category of keys. The list of all category names can be retrieved via |
| 140 |
the categories attribute. |
| 141 |
|
| 142 |
>>> for name in schema.category_names: |
| 143 |
... print(name) |
| 144 |
section-2 |
| 145 |
section_3 |
| 146 |
|
| 147 |
The list of SchemaSections that share common category can be retrieved |
| 148 |
using ``getByCategory()``. |
| 149 |
|
| 150 |
>>> all_section_3 = schema.getByCategory('section_3') |
| 151 |
>>> for section_schema in sorted(all_section_3, key=attrgetter('name')): |
| 152 |
... print(section_schema.name) |
| 153 |
section_3.app_a |
| 154 |
section_3.app_b |
| 155 |
|
| 156 |
You can pass a default argument to ``getByCategory()`` to avoid the exception. |
| 157 |
|
| 158 |
>>> missing = object() |
| 159 |
>>> schema.getByCategory('non-section', missing) is missing |
| 160 |
True |
| 161 |
|
| 162 |
|
| 163 |
SchemaSection |
| 164 |
============= |
| 165 |
|
| 166 |
A SchemaSection behaves similar to a dictionary. It has keys and values. |
| 167 |
|
| 168 |
>>> from lazr.config.interfaces import ISectionSchema |
| 169 |
>>> section_schema_1 = schema['section_1'] |
| 170 |
>>> verifyObject(ISectionSchema, section_schema_1) |
| 171 |
True |
| 172 |
|
| 173 |
Each SchemaSection has a name. |
| 174 |
|
| 175 |
>>> print(section_schema_1.name) |
| 176 |
section_1 |
| 177 |
|
| 178 |
A SchemaSection can return a 2-tuple of its category name and specific name |
| 179 |
parts. |
| 180 |
|
| 181 |
>>> for name in schema['section_3.app_b'].category_and_section_names: |
| 182 |
... print(name) |
| 183 |
section_3 |
| 184 |
app_b |
| 185 |
|
| 186 |
The category name will be ``None`` if the SchemaSection's name does not |
| 187 |
contain a category. |
| 188 |
|
| 189 |
>>> for name in section_schema_1.category_and_section_names: |
| 190 |
... print(name) |
| 191 |
None |
| 192 |
section_1 |
| 193 |
|
| 194 |
Optional sections have the optional attribute set to ``True``: |
| 195 |
|
| 196 |
>>> section_schema_1.optional |
| 197 |
False |
| 198 |
>>> schema['section_3.app_a'].optional |
| 199 |
True |
| 200 |
|
| 201 |
A key can be verified to be in a section. |
| 202 |
|
| 203 |
>>> 'key1' in section_schema_1 |
| 204 |
True |
| 205 |
>>> 'nonkey' in section_schema_1 |
| 206 |
False |
| 207 |
|
| 208 |
A key can be accessed directly using as a subscript of the SchemaSection. The |
| 209 |
value is always a string. |
| 210 |
|
| 211 |
>>> print(section_schema_1['key3']) |
| 212 |
Launchpad rocks |
| 213 |
>>> section_schema_1['key5'] |
| 214 |
'' |
| 215 |
|
| 216 |
An error is raised if a non-existent key is accessed. |
| 217 |
|
| 218 |
>>> section_schema_1['not-exist'] |
| 219 |
Traceback (most recent call last): |
| 220 |
... |
| 221 |
KeyError: ... |
| 222 |
|
| 223 |
In the conf file, ``[section_1]`` is a default section that defines keys and |
| 224 |
values. The values specified in the section schema will be used as default |
| 225 |
values if not overridden in the configuration. In the case of *key5*, the key |
| 226 |
had no explicit value, so the value is an empty string. |
| 227 |
|
| 228 |
>>> for key in sorted(section_schema_1): |
| 229 |
... print(key, ':', section_schema_1[key]) |
| 230 |
key1 : foo |
| 231 |
key2 : bar and baz |
| 232 |
key3 : Launchpad rocks |
| 233 |
key4 : Fc;k yeah! |
| 234 |
key5 : |
| 235 |
|
| 236 |
In the conf file ``[section_3.template]`` defines a common set of keys and |
| 237 |
default values for ``[section_3.app_a]`` and ``[section_3.app_b]``. When a |
| 238 |
section defines different keys and default values from the template, the new |
| 239 |
data overlays the template data. This is the case for section |
| 240 |
``[section_3.app_b]``. |
| 241 |
|
| 242 |
>>> for section_schema in sorted(all_section_3, key=attrgetter('name')): |
| 243 |
... print(section_schema.name) |
| 244 |
... for key in sorted(section_schema): |
| 245 |
... print(key, ':', section_schema[key]) |
| 246 |
section_3.app_a |
| 247 |
key1 : 17 |
| 248 |
key2 : 3.1415 |
| 249 |
section_3.app_b |
| 250 |
key1 : 17 |
| 251 |
key2 : changed |
| 252 |
key3 : unique |
| 253 |
|
| 254 |
|
| 255 |
ConfigSchema validation |
| 256 |
======================= |
| 257 |
|
| 258 |
The schema parser is self-validating. It checks that the character encoding |
| 259 |
is ASCII, and that the data is not ambiguous or self-contradicting. Keys must |
| 260 |
exist inside sections and section names may not be defined twice. Sections |
| 261 |
may belong to only one category, and only letters, numbers, dots and dashes |
| 262 |
may be present in section names. |
| 263 |
|
| 264 |
.. For multilingual Python support reasons, we don't include testable examples |
| 265 |
here. See ``test_config.py`` and ``lazr/config/interfaces.py`` for details. |
| 266 |
|
| 267 |
|
| 268 |
IConfigLoader |
| 269 |
============= |
| 270 |
|
| 271 |
ConfigSchema implements the two methods in the IConfigLoader interface. A |
| 272 |
Config is created by a schema using either the ``load()`` or ``loadFile()`` |
| 273 |
methods to return a Config instance. |
| 274 |
|
| 275 |
>>> from lazr.config.interfaces import IConfigLoader |
| 276 |
>>> verifyObject(IConfigLoader, schema) |
| 277 |
True |
| 278 |
|
| 279 |
The ``load()`` method accepts a filename. |
| 280 |
|
| 281 |
>>> local_conf = str(Path(_spec.origin).parent / 'local.conf') |
| 282 |
>>> config = schema.load(local_conf) |
| 283 |
|
| 284 |
The ``loadFile()`` method accepts a file-like object and an optional filename |
| 285 |
keyword argument. The filename argument must be passed if the file-like |
| 286 |
object does not have a ``name`` attribute. |
| 287 |
|
| 288 |
>>> try: |
| 289 |
... from io import StringIO |
| 290 |
... except ImportError: |
| 291 |
... # Python 2 |
| 292 |
... from StringIO import StringIO |
| 293 |
>>> bad_data = (""" |
| 294 |
... [meta] |
| 295 |
... metakey: unsupported |
| 296 |
... [unknown-section] |
| 297 |
... key1 = value1 |
| 298 |
... [section_1] |
| 299 |
... keyn: unknown key |
| 300 |
... key1: bad character in caf\xc3) |
| 301 |
... [section_3.template] |
| 302 |
... key1: schema suffixes are not permitted""") |
| 303 |
>>> bad_config = schema.loadFile( |
| 304 |
... StringIO(bad_data), 'bad conf') |
| 305 |
|
| 306 |
.. The bad_config example will be used for validation tests. |
| 307 |
|
| 308 |
|
| 309 |
Config |
| 310 |
====== |
| 311 |
|
| 312 |
The config represents the local configuration of the process on a system. It |
| 313 |
is validated with a schema. It extends the schema, or other conf files, to |
| 314 |
define the specific differences from the extended files that are required to |
| 315 |
run the local processes. |
| 316 |
|
| 317 |
The object returned by ``load()`` provides both the ``IConfigData`` and |
| 318 |
``IStackableConfig`` interfaces. ``IConfigData`` is for read-only access to |
| 319 |
the configuration data. A process configuration is made up of a stack of |
| 320 |
different ``IConfigData``. The ``IStackableConfig`` interface provides the |
| 321 |
methods used to manipulate that stack of configuration overlays. |
| 322 |
|
| 323 |
>>> from lazr.config.interfaces import IConfigData, IStackableConfig |
| 324 |
>>> verifyObject(IConfigData, config) |
| 325 |
True |
| 326 |
>>> verifyObject(IStackableConfig, config) |
| 327 |
True |
| 328 |
|
| 329 |
Like the schema file, the conf file is made up of sections with keys. The |
| 330 |
sections may belong to a category. Unlike the schema file, it does not have |
| 331 |
template or optional sections. The ``[meta]`` section has the extends key |
| 332 |
that declares that this conf extends ``shared.conf``. |
| 333 |
|
| 334 |
>>> with open(local_conf, 'rt') as local_file: |
| 335 |
... raw_conf = local_file.read() |
| 336 |
>>> print(raw_conf) |
| 337 |
[meta] |
| 338 |
extends: shared.conf |
| 339 |
# Localize a key for section_1. |
| 340 |
[section_1] |
| 341 |
key5: local value |
| 342 |
# Accept the default values for the optional section-5. |
| 343 |
[section-5] |
| 344 |
|
| 345 |
The ``.master`` section allows admins to define configurations for an |
| 346 |
arbitrary number of processes. If the schema defines ``.master`` sections, |
| 347 |
then the conf file can contain sections that extend the ``.master`` section. |
| 348 |
These are like categories with templates except that the section names |
| 349 |
extending ``.master`` need not be named in the schema file. |
| 350 |
|
| 351 |
>>> master_schema_conf = str(Path(_spec.origin).parent / 'master.conf') |
| 352 |
>>> master_local_conf = str(Path(_spec.origin).parent / 'master-local.conf') |
| 353 |
>>> master_schema = ConfigSchema(master_schema_conf) |
| 354 |
>>> sections = master_schema.getByCategory('thing') |
| 355 |
>>> for name in sorted(section.name for section in sections): |
| 356 |
... print(name) |
| 357 |
thing.master |
| 358 |
>>> master_conf = master_schema.load(master_local_conf) |
| 359 |
>>> sections = master_conf.getByCategory('thing') |
| 360 |
>>> for name in sorted(section.name for section in sections): |
| 361 |
... print(name) |
| 362 |
thing.one |
| 363 |
thing.two |
| 364 |
>>> for name in sorted(section.foo for section in sections): |
| 365 |
... print(name) |
| 366 |
1 |
| 367 |
2 |
| 368 |
>>> print(master_conf.thing.one.name) |
| 369 |
thing.one |
| 370 |
|
| 371 |
The ``shared.conf`` file derives the keys and default values from the schema. |
| 372 |
This config was loaded before ``local.conf`` because its sections and values |
| 373 |
are required to be in place before ``local.conf`` applies its changes. |
| 374 |
|
| 375 |
>>> shared_config = str(Path(_spec.origin).parent / 'shared.conf') |
| 376 |
>>> with open(shared_config, 'rt') as shared_file: |
| 377 |
... raw_conf = shared_file.read() |
| 378 |
>>> print(raw_conf) |
| 379 |
# The schema is defined by base.conf. |
| 380 |
# Localize a key for section_1. |
| 381 |
[section_1] |
| 382 |
key2: sharing is fun |
| 383 |
key5: shared value |
| 384 |
|
| 385 |
The config that was loaded has ``name`` and ``filename`` attributes to |
| 386 |
identify the configuration. |
| 387 |
|
| 388 |
>>> print(config.name) |
| 389 |
local.conf |
| 390 |
>>> print('file:', config.filename) |
| 391 |
file: ...lazr/config/tests/testdata/local.conf |
| 392 |
|
| 393 |
The config can access the schema via the schema property. |
| 394 |
|
| 395 |
>>> print(config.schema.name) |
| 396 |
base.conf |
| 397 |
>>> config.schema is schema |
| 398 |
True |
| 399 |
|
| 400 |
A config is made up of multiple Sections like the schema. They can be |
| 401 |
iterated over in a loop as needed. This config inherited several sections |
| 402 |
defined in schema. Note that the meta section is not present because it |
| 403 |
pertains to the config system, not to the processes being configured. |
| 404 |
|
| 405 |
>>> for section in sorted(config, key=attrgetter('name')): |
| 406 |
... print(section.name) |
| 407 |
section-2.app-b |
| 408 |
section-5 |
| 409 |
section_1 |
| 410 |
section_3.app_b |
| 411 |
section_33 |
| 412 |
|
| 413 |
You can check if a section name is in a config. |
| 414 |
|
| 415 |
>>> 'section_1' in config |
| 416 |
True |
| 417 |
>>> 'bad-section' in config |
| 418 |
False |
| 419 |
|
| 420 |
Optional SchemaSections are not inherited by the config. A config file must |
| 421 |
declare all optional sections. Including the section heading is enough to |
| 422 |
inherit the section and its keys. The config file may localize the keys by |
| 423 |
declaring them too. The ``local.conf`` file includes ``section-5``, but not |
| 424 |
``section_3.app_a``. |
| 425 |
|
| 426 |
|
| 427 |
>>> 'section_3.app_a' in config |
| 428 |
False |
| 429 |
>>> 'section_3.app_a' in config.schema |
| 430 |
True |
| 431 |
>>> config.schema['section_3.app_a'].optional |
| 432 |
True |
| 433 |
>>> 'section-5' in config |
| 434 |
True |
| 435 |
>>> 'section-5' in config.schema |
| 436 |
True |
| 437 |
>>> config.schema['section-5'].optional |
| 438 |
True |
| 439 |
|
| 440 |
A Section can be accessed using subscript notation. Accessing a section that |
| 441 |
does not exist will raise a NoSectionError. NoSectionError is raised for a |
| 442 |
undeclared optional sections too. |
| 443 |
|
| 444 |
>>> section_1 = config['section_1'] |
| 445 |
>>> section_1.name in config |
| 446 |
True |
| 447 |
|
| 448 |
Config supports category access like Schema does. The list of categories are |
| 449 |
returned by the ``category_names`` property. |
| 450 |
|
| 451 |
>>> for name in sorted(config.category_names): |
| 452 |
... print(name) |
| 453 |
section-2 |
| 454 |
section_3 |
| 455 |
|
| 456 |
All the sections that belong to a category can be retrieved using the |
| 457 |
``getByCategory()`` method. |
| 458 |
|
| 459 |
>>> for section in config.getByCategory('section_3'): |
| 460 |
... print(section_schema.name) |
| 461 |
section_3.app_b |
| 462 |
|
| 463 |
Passing a non-existent category_name to the method will raise a |
| 464 |
NoCategoryError. As with schemas, you can pass a default argument to |
| 465 |
``getByCategory()`` to avoid the exception. |
| 466 |
|
| 467 |
>>> missing = object() |
| 468 |
>>> config.getByCategory('non-section', missing) is missing |
| 469 |
True |
| 470 |
|
| 471 |
|
| 472 |
Section |
| 473 |
======= |
| 474 |
|
| 475 |
A Section behaves similar to a dictionary. It has keys and values. It |
| 476 |
supports some specialize access methods and properties for working with the |
| 477 |
values. Each Section has a name. |
| 478 |
|
| 479 |
>>> from lazr.config.interfaces import ISection |
| 480 |
>>> verifyObject(ISection, section_1) |
| 481 |
True |
| 482 |
>>> print(section_1.name) |
| 483 |
section_1 |
| 484 |
|
| 485 |
Like SectionSchemas, sections can return a 2-tuple of their category name and |
| 486 |
specific name parts. The category name will be ``None`` if the section's name |
| 487 |
does not contain a category. |
| 488 |
|
| 489 |
>>> for name in config['section_3.app_b'].category_and_section_names: |
| 490 |
... print(name) |
| 491 |
section_3 |
| 492 |
app_b |
| 493 |
>>> for name in section_1.category_and_section_names: |
| 494 |
... print(name) |
| 495 |
None |
| 496 |
section_1 |
| 497 |
|
| 498 |
The Section's type is the same type as the ``ConfigSchema.section_factory``. |
| 499 |
|
| 500 |
>>> section_1 |
| 501 |
<lazr.config...Section object at ...> |
| 502 |
>>> config.schema.section_factory |
| 503 |
<class 'lazr.config...Section'> |
| 504 |
|
| 505 |
A key can be verified to be in a Section. |
| 506 |
|
| 507 |
>>> 'key1' in section_1 |
| 508 |
True |
| 509 |
>>> 'nonkey' in section_1 |
| 510 |
False |
| 511 |
|
| 512 |
A key can be accessed directly using as a subscript of the Section. |
| 513 |
The value is always a string. |
| 514 |
|
| 515 |
>>> print(section_1['key3']) |
| 516 |
Launchpad rocks |
| 517 |
>>> print(section_1['key5']) |
| 518 |
local value |
| 519 |
|
| 520 |
An error is raised if a non-existent key is accessed via a subscript. |
| 521 |
|
| 522 |
>>> section_1['not-exist'] |
| 523 |
Traceback (most recent call last): |
| 524 |
... |
| 525 |
KeyError: ... |
| 526 |
|
| 527 |
The Section keys can be iterated over. The section has all the keys from the |
| 528 |
SectionSchema. The values came form the schema's default values, then the |
| 529 |
values from ``shared.conf`` were applied, and lastly, the values from |
| 530 |
``local.conf`` were applied. The schema provided the values of ``key1``, |
| 531 |
``key3``, and ``key4``. ``shared.conf`` provided the value of ``key2`` |
| 532 |
. ``local.conf`` provided ``key5``. While ``shared.conf`` provided a |
| 533 |
``key5``, ``local.conf`` takes precedence. |
| 534 |
|
| 535 |
>>> for key in sorted(section_1): |
| 536 |
... print(key, ':', section_1[key]) |
| 537 |
key1 : foo |
| 538 |
key2 : sharing is fun |
| 539 |
key3 : Launchpad rocks |
| 540 |
key4 : Fc;k yeah! |
| 541 |
key5 : local value |
| 542 |
>>> section_1.schema['key5'] |
| 543 |
'' |
| 544 |
|
| 545 |
The schema provided mandatory sections and default values to the config. So |
| 546 |
while the config file did not declare all the sections, they are present. In |
| 547 |
the case of ``section_3.app_b``, its keys were defined in a template section. |
| 548 |
|
| 549 |
>>> for key in sorted(config['section_3.app_b']): |
| 550 |
... print(key, ':', config['section_3.app_b'][key]) |
| 551 |
key1 : 17 |
| 552 |
key2 : changed |
| 553 |
key3 : unique |
| 554 |
|
| 555 |
Sections attributes cannot be directly set to shadow config options. An |
| 556 |
``AttributeError`` is raised when an attempt is made to mutate the config. |
| 557 |
|
| 558 |
>>> config['section_3.app_b'].key1 = 'fail' |
| 559 |
Traceback (most recent call last): |
| 560 |
... |
| 561 |
AttributeError: Config options cannot be set directly. |
| 562 |
|
| 563 |
Nor can new attributes be added to a section. |
| 564 |
|
| 565 |
>>> config['section_3.app_b'].no_such_attribute = 'fail' |
| 566 |
Traceback (most recent call last): |
| 567 |
... |
| 568 |
AttributeError: Config options cannot be set directly. |
| 569 |
|
| 570 |
|
| 571 |
Validating configs |
| 572 |
================== |
| 573 |
|
| 574 |
Config provides the ``validate()`` method to verify that the config is valid |
| 575 |
according to the schema. The method returns ``True`` if the config is valid. |
| 576 |
|
| 577 |
>>> config.validate() |
| 578 |
True |
| 579 |
|
| 580 |
When the config is not valid, a ConfigErrors is raised. The exception has an |
| 581 |
``errors`` property that contains a list of all the errors in the config. |
| 582 |
|
| 583 |
|
| 584 |
Config overlays |
| 585 |
=============== |
| 586 |
|
| 587 |
A conf file may contain a meta section that is used by the config system. The |
| 588 |
config data can access the config it extended using the ``extends`` property. |
| 589 |
The object is just the config data; it does not have any config methods. |
| 590 |
|
| 591 |
>>> print(config.extends.name) |
| 592 |
shared.conf |
| 593 |
|
| 594 |
>>> verifyObject(IConfigData, config.extends) |
| 595 |
True |
| 596 |
|
| 597 |
As Config supports inheritance through the ``extends`` key, each conf file |
| 598 |
produces instance of ConfigData, called an *overlay*. ConfigData represents |
| 599 |
the state of a config. The ``overlays`` property is a stack of ConfigData as |
| 600 |
it was constructed from the schema's config to the last config file that was |
| 601 |
loaded. |
| 602 |
|
| 603 |
>>> for config_data in config.overlays: |
| 604 |
... print(config_data.name) |
| 605 |
local.conf |
| 606 |
shared.conf |
| 607 |
base.conf |
| 608 |
>>> verifyObject(IConfigData, config.overlays[-1]) |
| 609 |
True |
| 610 |
|
| 611 |
Conf files can use the ``extends`` key to specify that it extends a schema |
| 612 |
without incurring a processing penalty by loading the schema twice in a row. |
| 613 |
The schema can never be the second item in the overlays stack. |
| 614 |
|
| 615 |
>>> single_config = schema.load(schema.filename) |
| 616 |
>>> for config_data in single_config.overlays: |
| 617 |
... print(config_data.name) |
| 618 |
base.conf |
| 619 |
>>> single_config.push(schema.filename, raw_schema.decode('utf-8')) |
| 620 |
>>> for config_data in single_config.overlays: |
| 621 |
... print(config_data.name) |
| 622 |
base.conf |
| 623 |
|
| 624 |
|
| 625 |
push() |
| 626 |
====== |
| 627 |
|
| 628 |
Raw config data can be merged with the config to create a new overlay for |
| 629 |
testing. The ``push()`` method accepts a string of config data. The data |
| 630 |
must conform to the schema. The ``section_1`` sections's keys are updated |
| 631 |
when the unparsed data is pushed onto the config. Note that indented, |
| 632 |
unparsed data is passed to ``push()`` in this example; ``push()`` does not |
| 633 |
require tests to dedent the test data. |
| 634 |
:: |
| 635 |
|
| 636 |
>>> for key in sorted(config['section_1']): |
| 637 |
... print(key, ':', config['section_1'][key]) |
| 638 |
key1 : foo |
| 639 |
key2 : sharing is fun |
| 640 |
key3 : Launchpad rocks |
| 641 |
key4 : Fc;k yeah! |
| 642 |
key5 : local value |
| 643 |
|
| 644 |
>>> test_data = (""" |
| 645 |
... [section_1] |
| 646 |
... key1: test1 |
| 647 |
... key5:""") |
| 648 |
>>> config.push('test config', test_data) |
| 649 |
|
| 650 |
>>> for key in sorted(config['section_1']): |
| 651 |
... print(key, ':', config['section_1'][key]) |
| 652 |
key1 : test1 |
| 653 |
key2 : sharing is fun |
| 654 |
key3 : Launchpad rocks |
| 655 |
key4 : Fc;k yeah! |
| 656 |
key5 : |
| 657 |
|
| 658 |
Besides updating section keys, optional sections can be enabled too. The |
| 659 |
``section_3.app_a`` section is enabled with the default keys from the schema |
| 660 |
in this example. |
| 661 |
:: |
| 662 |
|
| 663 |
>>> config.schema['section_3.app_a'].optional |
| 664 |
True |
| 665 |
>>> 'section_3.app_a' in config |
| 666 |
False |
| 667 |
|
| 668 |
>>> app_a_data = "[section_3.app_a]" |
| 669 |
>>> config.push('test app_a', app_a_data) |
| 670 |
|
| 671 |
>>> 'section_3.app_a' in config |
| 672 |
True |
| 673 |
>>> for key in sorted(config['section_3.app_a']): |
| 674 |
... print(key, ':', config['section_3.app_a'][key]) |
| 675 |
key1 : 17 |
| 676 |
key2 : 3.1415 |
| 677 |
|
| 678 |
>>> for key in sorted(config.schema['section_3.app_a']): |
| 679 |
... print(key, ':', config.schema['section_3.app_a'][key]) |
| 680 |
key1 : 17 |
| 681 |
key2 : 3.1415 |
| 682 |
|
| 683 |
The config's name and overlays are updated by ``push()``. |
| 684 |
|
| 685 |
>>> print(config.name) |
| 686 |
test app_a |
| 687 |
>>> print(config.filename) |
| 688 |
test app_a |
| 689 |
>>> for config_data in config.overlays: |
| 690 |
... print(config_data.name) |
| 691 |
test app_a |
| 692 |
test config |
| 693 |
local.conf |
| 694 |
shared.conf |
| 695 |
base.conf |
| 696 |
|
| 697 |
The ``test app_a`` config did not declare an ``extends`` key in a ``meta`` |
| 698 |
section. Its ``extends`` property is ``None``, even though it implicitly |
| 699 |
extends ``test config``. The ``extends`` property only provides access to |
| 700 |
configs that are explicitly extended. |
| 701 |
|
| 702 |
>>> print(config.extends.name) |
| 703 |
test config |
| 704 |
|
| 705 |
The config's sections are updated with ``section_3.app_a`` too. |
| 706 |
|
| 707 |
>>> for section in sorted(config, key=attrgetter('name')): |
| 708 |
... print(section.name) |
| 709 |
section-2.app-b |
| 710 |
section-5 |
| 711 |
section_1 |
| 712 |
section_3.app_a |
| 713 |
section_3.app_b |
| 714 |
section_33 |
| 715 |
|
| 716 |
A config file may state that it extends its schema (to clearly connect the |
| 717 |
config to the schema). The schema can also be pushed to reset the values in |
| 718 |
the config to the schema's default values. |
| 719 |
|
| 720 |
>>> extender_conf_name = str(Path(_spec.origin).parent / 'extender.conf') |
| 721 |
>>> extender_conf_data = (""" |
| 722 |
... [meta] |
| 723 |
... extends: base.conf""") |
| 724 |
>>> config.push(extender_conf_name, extender_conf_data) |
| 725 |
>>> for config_data in config.overlays: |
| 726 |
... print(config_data.name) |
| 727 |
extender.conf |
| 728 |
base.conf |
| 729 |
test app_a |
| 730 |
test config |
| 731 |
local.conf |
| 732 |
shared.conf |
| 733 |
base.conf |
| 734 |
|
| 735 |
The ``section_1`` section was restored to the schema's default values. |
| 736 |
|
| 737 |
>>> for key in sorted(config['section_1']): |
| 738 |
... print(key, ':', config['section_1'][key]) |
| 739 |
key1 : foo |
| 740 |
key2 : bar and baz |
| 741 |
key3 : Launchpad rocks |
| 742 |
key4 : Fc;k yeah! |
| 743 |
key5 : |
| 744 |
|
| 745 |
``push()`` can also be used to extend master sections. |
| 746 |
:: |
| 747 |
|
| 748 |
>>> sections = sorted(master_conf.getByCategory('bar'), |
| 749 |
... key=attrgetter('name')) |
| 750 |
>>> for section in sections: |
| 751 |
... print(section.name, section.baz) |
| 752 |
bar.master badger |
| 753 |
bar.soup cougar |
| 754 |
|
| 755 |
>>> master_conf.push('override', """ |
| 756 |
... [bar.two] |
| 757 |
... baz: dolphin |
| 758 |
... """) |
| 759 |
>>> sections = sorted(master_conf.getByCategory('bar'), |
| 760 |
... key=attrgetter('name')) |
| 761 |
>>> for section in sections: |
| 762 |
... print(section.name, section.baz) |
| 763 |
bar.soup cougar |
| 764 |
bar.two dolphin |
| 765 |
|
| 766 |
>>> master_conf.push('overlord', """ |
| 767 |
... [bar.three] |
| 768 |
... baz: emu |
| 769 |
... """) |
| 770 |
>>> sections = sorted(master_conf.getByCategory('bar'), |
| 771 |
... key=attrgetter('name')) |
| 772 |
>>> for section in sections: |
| 773 |
... print(section.name, section.baz) |
| 774 |
bar.soup cougar |
| 775 |
bar.three emu |
| 776 |
bar.two dolphin |
| 777 |
|
| 778 |
``push()`` works with master sections too. |
| 779 |
:: |
| 780 |
|
| 781 |
>>> schema_file = StringIO("""\ |
| 782 |
... [thing.master] |
| 783 |
... foo: 0 |
| 784 |
... bar: 0 |
| 785 |
... """) |
| 786 |
>>> push_schema = ConfigSchema('schema.cfg', schema_file) |
| 787 |
|
| 788 |
>>> config_file = StringIO("""\ |
| 789 |
... [thing.one] |
| 790 |
... foo: 1 |
| 791 |
... """) |
| 792 |
>>> push_config = push_schema.loadFile(config_file, 'config.cfg') |
| 793 |
>>> print(push_config.thing.one.foo) |
| 794 |
1 |
| 795 |
>>> print(push_config.thing.one.bar) |
| 796 |
0 |
| 797 |
|
| 798 |
>>> push_config.push('test.cfg', """\ |
| 799 |
... [thing.one] |
| 800 |
... bar: 2 |
| 801 |
... """) |
| 802 |
>>> print(push_config.thing.one.foo) |
| 803 |
1 |
| 804 |
>>> print(push_config.thing.one.bar) |
| 805 |
2 |
| 806 |
|
| 807 |
|
| 808 |
pop() |
| 809 |
===== |
| 810 |
|
| 811 |
ConfigData can be removed from the stack of overlays using the ``pop()`` |
| 812 |
method. The methods returns the list of ConfigData that was removed -- a |
| 813 |
slice from the specified ConfigData to the top of the stack. |
| 814 |
:: |
| 815 |
|
| 816 |
>>> overlays = config.pop('test config') |
| 817 |
>>> for config_data in overlays: |
| 818 |
... print(config_data.name) |
| 819 |
extender.conf |
| 820 |
base.conf |
| 821 |
test app_a |
| 822 |
test config |
| 823 |
|
| 824 |
>>> for config_data in config.overlays: |
| 825 |
... print(config_data.name) |
| 826 |
local.conf |
| 827 |
shared.conf |
| 828 |
base.conf |
| 829 |
|
| 830 |
The config's state was restored to the ConfigData that is on top of the |
| 831 |
overlay stack. Section ``section_3.app_a`` was removed completely. The keys |
| 832 |
(``key1`` and ``key5``) for ``section_1`` were restored. |
| 833 |
:: |
| 834 |
|
| 835 |
>>> for section in sorted(config, key=attrgetter('name')): |
| 836 |
... print(section.name) |
| 837 |
section-2.app-b |
| 838 |
section-5 |
| 839 |
section_1 |
| 840 |
section_3.app_b |
| 841 |
section_33 |
| 842 |
|
| 843 |
>>> for key in sorted(config['section_1']): |
| 844 |
... print(key, ':', config['section_1'][key]) |
| 845 |
key1 : foo |
| 846 |
key2 : sharing is fun |
| 847 |
key3 : Launchpad rocks |
| 848 |
key4 : Fc;k yeah! |
| 849 |
key5 : local value |
| 850 |
|
| 851 |
A Config must have at least one ConfigData in the overlays stack so that it |
| 852 |
has data. The bottom ConfigData in the overlays was made from the schema's |
| 853 |
required sections. It cannot be removed by the ``pop()`` method. |
| 854 |
|
| 855 |
If all but the bottom ConfigData is popped from overlays, the extends |
| 856 |
property returns None. |
| 857 |
|
| 858 |
>>> overlays = config.pop('shared.conf') |
| 859 |
>>> print(config.extends) |
| 860 |
None |
| 861 |
|
| 862 |
|
| 863 |
Attribute access to config data |
| 864 |
=============================== |
| 865 |
|
| 866 |
Config provides attribute-based access to its members. So long as the |
| 867 |
section, category, and key names conform to Python identifier naming rules, |
| 868 |
they can be accessed as attributes. The Python code will not compile, or will |
| 869 |
cause a runtime error if the object being accessed has a bad name. |
| 870 |
|
| 871 |
Sections appear to be attributes of the config. |
| 872 |
|
| 873 |
>>> config = schema.load(local_conf) |
| 874 |
>>> config.section_1 is config['section_1'] |
| 875 |
True |
| 876 |
|
| 877 |
Accessing an unknown section, or a section whose name is not a valid Python |
| 878 |
identifier will raise an AttributeError. |
| 879 |
|
| 880 |
>>> config.section-5 |
| 881 |
Traceback (most recent call last): |
| 882 |
... |
| 883 |
AttributeError: No section or category named section. |
| 884 |
|
| 885 |
Categories may be accessed as attributes too. The ICategory interface |
| 886 |
provides access to its sections as members. |
| 887 |
|
| 888 |
>>> from lazr.config.interfaces import ICategory |
| 889 |
>>> config_category = config.section_3 |
| 890 |
>>> verifyObject(ICategory, config_category) |
| 891 |
True |
| 892 |
>>> config_category.app_b is config['section_3.app_b'] |
| 893 |
True |
| 894 |
|
| 895 |
Like a config, a category will raise an AttributeError if it does not have a |
| 896 |
section that matches the identifier name. |
| 897 |
|
| 898 |
>>> config_category.no_such_section |
| 899 |
Traceback (most recent call last): |
| 900 |
... |
| 901 |
AttributeError: No section named no_such_section. |
| 902 |
|
| 903 |
Section keys can be accessed directly as members. |
| 904 |
|
| 905 |
>>> print(config.section_1.key2) |
| 906 |
sharing is fun |
| 907 |
>>> print(config.section_3.app_b.key2) |
| 908 |
changed |
| 909 |
|
| 910 |
Accessing a non-existent section key as an attribute will raise an |
| 911 |
AttributeError. |
| 912 |
|
| 913 |
>>> config.section_1.non_key |
| 914 |
Traceback (most recent call last): |
| 915 |
... |
| 916 |
AttributeError: No section key named non_key. |
| 917 |
|
| 918 |
|
| 919 |
Implicit data typing |
| 920 |
==================== |
| 921 |
|
| 922 |
The ImplicitTypeSchema can create configs that support implicit datatypes. |
| 923 |
The value of a Section key is automatically converted from ``str`` to the type |
| 924 |
the value appears to be. Implicit typing does not add any validation support; |
| 925 |
it adds type casting conveniences for the developer. |
| 926 |
|
| 927 |
An ImplicitTypeSchema can be used to parse the same schema and conf files that |
| 928 |
Schema uses. |
| 929 |
|
| 930 |
>>> from lazr.config import ImplicitTypeSchema |
| 931 |
>>> implicit_schema = ImplicitTypeSchema(base_conf) |
| 932 |
>>> verifyObject(IConfigSchema, implicit_schema) |
| 933 |
True |
| 934 |
|
| 935 |
The config loaded by ImplicitTypeSchema is the same class with the same |
| 936 |
sections as is made by Schema. |
| 937 |
:: |
| 938 |
|
| 939 |
>>> implicit_config = implicit_schema.load(local_conf) |
| 940 |
>>> implicit_config |
| 941 |
<lazr.config...Config object at ...> |
| 942 |
>>> config |
| 943 |
<lazr.config...Config object at ...> |
| 944 |
|
| 945 |
>>> sections = sorted(section.name for section in config) |
| 946 |
>>> implicit_sections = sorted( |
| 947 |
... section.name for section in implicit_config) |
| 948 |
>>> implicit_sections == sections |
| 949 |
True |
| 950 |
|
| 951 |
>>> verifyObject(ISection, implicit_config['section_3.app_b']) |
| 952 |
True |
| 953 |
|
| 954 |
But the type of sections in the config support implicit typing. |
| 955 |
|
| 956 |
>>> implicit_config['section_3.app_b'] |
| 957 |
<lazr.config...ImplicitTypeSection object at ...> |
| 958 |
|
| 959 |
ImplicitTypeSection, in contrast to Section, converts values that appear to be |
| 960 |
integer or boolean into ints and bools. |
| 961 |
:: |
| 962 |
|
| 963 |
>>> config['section_3.app_b']['key1'] |
| 964 |
'17' |
| 965 |
>>> implicit_config['section_3.app_b']['key1'] |
| 966 |
17 |
| 967 |
|
| 968 |
>>> config['section-2.app-b']['key1'] |
| 969 |
'True' |
| 970 |
>>> implicit_config['section-2.app-b']['key1'] |
| 971 |
True |
| 972 |
|
| 973 |
The value is also converted when it is accessed as an attribute. |
| 974 |
|
| 975 |
>>> implicit_config.section_3.app_b.key1 |
| 976 |
17 |
| 977 |
|
| 978 |
>>> implicit_config['section-2.app-b'].key1 |
| 979 |
True |
| 980 |
|
| 981 |
ImplicitTypeSection uses a private method that employs heuristic rules to |
| 982 |
convert strings into simple types. It may return a str, bool, or int. When |
| 983 |
the argument is the word 'true' or 'false' (in any case), a bool is returned. |
| 984 |
Values like 'yes', 'no', '0', and '1' are not converted to bool. |
| 985 |
:: |
| 986 |
|
| 987 |
>>> convert = implicit_config['section_1']._convert |
| 988 |
|
| 989 |
>>> convert('false') |
| 990 |
False |
| 991 |
>>> convert('TRUE') |
| 992 |
True |
| 993 |
>>> convert('tRue') |
| 994 |
True |
| 995 |
|
| 996 |
>>> print(convert('yes')) |
| 997 |
yes |
| 998 |
>>> convert('1') |
| 999 |
1 |
| 1000 |
>>> print(convert('True or False')) |
| 1001 |
True or False |
| 1002 |
|
| 1003 |
When the argument is the word ``none``, ``None`` is returned. The token in |
| 1004 |
the config means the key has no value. |
| 1005 |
:: |
| 1006 |
|
| 1007 |
>>> print(convert('none')) |
| 1008 |
None |
| 1009 |
>>> print(convert('None')) |
| 1010 |
None |
| 1011 |
>>> print(convert('nonE')) |
| 1012 |
None |
| 1013 |
|
| 1014 |
>>> print(convert('none today')) |
| 1015 |
none today |
| 1016 |
>>> print(convert('nonevident')) |
| 1017 |
nonevident |
| 1018 |
|
| 1019 |
When the argument is an unbroken sequence of numbers, an int is returned. The |
| 1020 |
number may have a leading positive or negative. Octal and hex notation is not |
| 1021 |
supported. |
| 1022 |
:: |
| 1023 |
|
| 1024 |
>>> convert('0') |
| 1025 |
0 |
| 1026 |
>>> convert('2001') |
| 1027 |
2001 |
| 1028 |
>>> convert('-55') |
| 1029 |
-55 |
| 1030 |
>>> convert('+404') |
| 1031 |
404 |
| 1032 |
>>> convert('0100') |
| 1033 |
100 |
| 1034 |
|
| 1035 |
>>> print(convert('2001-01-01')) |
| 1036 |
2001-01-01 |
| 1037 |
>>> print(convert('1000*60*5')) |
| 1038 |
1000*60*5 |
| 1039 |
>>> print(convert('1000 * 60 * 5')) |
| 1040 |
1000 * 60 * 5 |
| 1041 |
>>> print(convert('1,024')) |
| 1042 |
1,024 |
| 1043 |
>>> print(convert('0.5')) |
| 1044 |
0.5 |
| 1045 |
>>> print(convert('0x100')) |
| 1046 |
0x100 |
| 1047 |
|
| 1048 |
Multiline values are always strings, with white space (and line breaks) |
| 1049 |
removed from the beginning and end. |
| 1050 |
|
| 1051 |
>>> print(convert("""multiline value 1 |
| 1052 |
... multiline value 2""")) |
| 1053 |
multiline value 1 |
| 1054 |
multiline value 2 |
| 1055 |
|
| 1056 |
|
| 1057 |
Type conversion helpers |
| 1058 |
======================= |
| 1059 |
|
| 1060 |
lazr.config provides a few helpers for doing explicit type conversion. These |
| 1061 |
functions have to be imported and called explicitly on the configuration |
| 1062 |
variable values. |
| 1063 |
|
| 1064 |
|
| 1065 |
Booleans |
| 1066 |
-------- |
| 1067 |
|
| 1068 |
There is a helper for turning various strings into the boolean values ``True`` |
| 1069 |
and ``False``. |
| 1070 |
|
| 1071 |
>>> from lazr.config import as_boolean |
| 1072 |
|
| 1073 |
True values include (case-insensitively): true, yes, 1, on, enabled, and |
| 1074 |
enable. |
| 1075 |
|
| 1076 |
>>> for value in ('true', 'yes', 'on', 'enable', 'enabled', '1'): |
| 1077 |
... print(value, '->', as_boolean(value)) |
| 1078 |
... print(value.upper(), '->', as_boolean(value.upper())) |
| 1079 |
true -> True |
| 1080 |
TRUE -> True |
| 1081 |
yes -> True |
| 1082 |
YES -> True |
| 1083 |
on -> True |
| 1084 |
ON -> True |
| 1085 |
enable -> True |
| 1086 |
ENABLE -> True |
| 1087 |
enabled -> True |
| 1088 |
ENABLED -> True |
| 1089 |
1 -> True |
| 1090 |
1 -> True |
| 1091 |
|
| 1092 |
False values include (case-insensitively): false, no, 0, off, disabled, and |
| 1093 |
disable. |
| 1094 |
|
| 1095 |
>>> for value in ('false', 'no', 'off', 'disable', 'disabled', '0'): |
| 1096 |
... print(value, '->', as_boolean(value)) |
| 1097 |
... print(value.upper(), '->', as_boolean(value.upper())) |
| 1098 |
false -> False |
| 1099 |
FALSE -> False |
| 1100 |
no -> False |
| 1101 |
NO -> False |
| 1102 |
off -> False |
| 1103 |
OFF -> False |
| 1104 |
disable -> False |
| 1105 |
DISABLE -> False |
| 1106 |
disabled -> False |
| 1107 |
DISABLED -> False |
| 1108 |
0 -> False |
| 1109 |
0 -> False |
| 1110 |
|
| 1111 |
Anything else is a error. |
| 1112 |
|
| 1113 |
>>> as_boolean('cheese') |
| 1114 |
Traceback (most recent call last): |
| 1115 |
... |
| 1116 |
ValueError: Invalid boolean value: cheese |
| 1117 |
|
| 1118 |
|
| 1119 |
Host and port |
| 1120 |
------------- |
| 1121 |
|
| 1122 |
There is a helper for converting from a ``host:port`` string to a 2-tuple of |
| 1123 |
``(host, port)``. |
| 1124 |
|
| 1125 |
>>> from lazr.config import as_host_port |
| 1126 |
>>> host, port = as_host_port('host:25') |
| 1127 |
>>> print(host, port) |
| 1128 |
host 25 |
| 1129 |
|
| 1130 |
The port string is optional, in which case, port 25 is the default (for |
| 1131 |
historical reasons). |
| 1132 |
|
| 1133 |
>>> host, port = as_host_port('host') |
| 1134 |
>>> print(host, port) |
| 1135 |
host 25 |
| 1136 |
|
| 1137 |
The default port can be overridden. |
| 1138 |
|
| 1139 |
>>> host, port = as_host_port('host', default_port=22) |
| 1140 |
>>> print(host, port) |
| 1141 |
host 22 |
| 1142 |
|
| 1143 |
The default port is ignored if it is given in the value. |
| 1144 |
|
| 1145 |
>>> host, port = as_host_port('host:80', default_port=22) |
| 1146 |
>>> print(host, port) |
| 1147 |
host 80 |
| 1148 |
|
| 1149 |
The host name is also optional, as denoted by a leading colon. When omitted, |
| 1150 |
localhost is used. |
| 1151 |
|
| 1152 |
>>> host, port = as_host_port(':80') |
| 1153 |
>>> print(host, port) |
| 1154 |
localhost 80 |
| 1155 |
|
| 1156 |
The default host name can be overridden though. |
| 1157 |
|
| 1158 |
>>> host, port = as_host_port(':80', default_host='myhost') |
| 1159 |
>>> print(host, port) |
| 1160 |
myhost 80 |
| 1161 |
|
| 1162 |
The default host name is ignored if the value string contains it. |
| 1163 |
|
| 1164 |
>>> host, port = as_host_port('yourhost:80', default_host='myhost') |
| 1165 |
>>> print(host, port) |
| 1166 |
yourhost 80 |
| 1167 |
|
| 1168 |
A ValueError occurs if the port number in the configuration value string is |
| 1169 |
not an integer. |
| 1170 |
|
| 1171 |
>>> as_host_port(':foo') |
| 1172 |
Traceback (most recent call last): |
| 1173 |
... |
| 1174 |
ValueError: invalid literal for int...foo... |
| 1175 |
|
| 1176 |
|
| 1177 |
User and group |
| 1178 |
-------------- |
| 1179 |
|
| 1180 |
A helper is provided for turning a ``chown(1)``-style ``user:group`` |
| 1181 |
specification into a 2-tuple of the user name and group name. |
| 1182 |
|
| 1183 |
>>> from lazr.config import as_username_groupname |
| 1184 |
|
| 1185 |
The value string must contain both a user name and group name, separated by a |
| 1186 |
colon, otherwise an exception is raised. |
| 1187 |
|
| 1188 |
>>> as_username_groupname('foo') |
| 1189 |
Traceback (most recent call last): |
| 1190 |
... |
| 1191 |
ValueError: ... |
| 1192 |
|
| 1193 |
When both are given, the strings are returned unchanged or validated. |
| 1194 |
|
| 1195 |
>>> user, group = as_username_groupname('person:group') |
| 1196 |
>>> print(user, group) |
| 1197 |
person group |
| 1198 |
|
| 1199 |
Numeric values can be given, but they are not converted into their symbolic |
| 1200 |
names. |
| 1201 |
|
| 1202 |
>>> uid, gid = as_username_groupname('25:26') |
| 1203 |
>>> print(uid, gid) |
| 1204 |
25 26 |
| 1205 |
|
| 1206 |
By default the current user and group names are returned. |
| 1207 |
|
| 1208 |
>>> import grp, os, pwd |
| 1209 |
>>> user, group = as_username_groupname() |
| 1210 |
>>> user == pwd.getpwuid(os.getuid()).pw_name |
| 1211 |
True |
| 1212 |
>>> group == grp.getgrgid(os.getgid()).gr_name |
| 1213 |
True |
| 1214 |
|
| 1215 |
|
| 1216 |
Time intervals |
| 1217 |
-------------- |
| 1218 |
|
| 1219 |
This converter accepts a range of *time interval specifications*, and returns |
| 1220 |
a Python timedelta_. |
| 1221 |
|
| 1222 |
>>> from lazr.config import as_timedelta |
| 1223 |
|
| 1224 |
The function converts from an integer to the equivalent number of seconds. |
| 1225 |
|
| 1226 |
>>> as_timedelta('45s') |
| 1227 |
datetime.timedelta(...) |
| 1228 |
>>> print(as_timedelta('45s')) |
| 1229 |
0:00:45 |
| 1230 |
|
| 1231 |
The function also accepts suffixes ``m`` for minutes... |
| 1232 |
|
| 1233 |
>>> print(as_timedelta('3m')) |
| 1234 |
0:03:00 |
| 1235 |
|
| 1236 |
...``h`` for hours... |
| 1237 |
|
| 1238 |
>>> print(as_timedelta('2h')) |
| 1239 |
2:00:00 |
| 1240 |
|
| 1241 |
...and ``d`` for days... |
| 1242 |
|
| 1243 |
>>> print(as_timedelta('4d')) |
| 1244 |
4 days, 0:00:00 |
| 1245 |
|
| 1246 |
...and ``w`` for weeks. |
| 1247 |
|
| 1248 |
>>> print(as_timedelta('4w')) |
| 1249 |
28 days, 0:00:00 |
| 1250 |
|
| 1251 |
The function accepts a fractional number of seconds, indicating microseconds. |
| 1252 |
|
| 1253 |
>>> print(as_timedelta('3.2s')) |
| 1254 |
0:00:03.200000 |
| 1255 |
|
| 1256 |
It also accepts any combination thereof. |
| 1257 |
|
| 1258 |
>>> print(as_timedelta('3m22.5s')) |
| 1259 |
0:03:22.500000 |
| 1260 |
>>> print(as_timedelta('4w2d9h3s')) |
| 1261 |
30 days, 9:00:03 |
| 1262 |
|
| 1263 |
But doesn't accept "weird" or duplicate combinations. |
| 1264 |
|
| 1265 |
>>> as_timedelta('3s2s') |
| 1266 |
Traceback (most recent call last): |
| 1267 |
... |
| 1268 |
ValueError |
| 1269 |
>>> as_timedelta('2.9s4w') |
| 1270 |
Traceback (most recent call last): |
| 1271 |
... |
| 1272 |
ValueError |
| 1273 |
>>> as_timedelta('m') |
| 1274 |
Traceback (most recent call last): |
| 1275 |
... |
| 1276 |
ValueError |
| 1277 |
>>> as_timedelta('3m2') |
| 1278 |
Traceback (most recent call last): |
| 1279 |
... |
| 1280 |
ValueError |
| 1281 |
>>> as_timedelta('45') |
| 1282 |
Traceback (most recent call last): |
| 1283 |
... |
| 1284 |
ValueError |
| 1285 |
>>> as_timedelta('45wm') |
| 1286 |
Traceback (most recent call last): |
| 1287 |
... |
| 1288 |
ValueError |
| 1289 |
>>> as_timedelta('45z') |
| 1290 |
Traceback (most recent call last): |
| 1291 |
... |
| 1292 |
ValueError |
| 1293 |
|
| 1294 |
|
| 1295 |
Log levels |
| 1296 |
---------- |
| 1297 |
|
| 1298 |
It's convenient to be able to use symbolic log level names when using |
| 1299 |
``lazr.config`` to configure the Python logger. |
| 1300 |
|
| 1301 |
>>> from lazr.config import as_log_level |
| 1302 |
|
| 1303 |
Any symbolic log level value is valid to use, case insensitively. |
| 1304 |
|
| 1305 |
>>> for value in ('critical', 'error', 'warning', 'info', |
| 1306 |
... 'debug', 'notset'): |
| 1307 |
... print(value, '->', as_log_level(value)) |
| 1308 |
... print(value.upper(), '->', as_log_level(value.upper())) |
| 1309 |
critical -> 50 |
| 1310 |
CRITICAL -> 50 |
| 1311 |
error -> 40 |
| 1312 |
ERROR -> 40 |
| 1313 |
warning -> 30 |
| 1314 |
WARNING -> 30 |
| 1315 |
info -> 20 |
| 1316 |
INFO -> 20 |
| 1317 |
debug -> 10 |
| 1318 |
DEBUG -> 10 |
| 1319 |
notset -> 0 |
| 1320 |
NOTSET -> 0 |
| 1321 |
|
| 1322 |
Non-log levels cannot be used here. |
| 1323 |
|
| 1324 |
>>> as_log_level('cheese') |
| 1325 |
Traceback (most recent call last): |
| 1326 |
... |
| 1327 |
AttributeError: ... |
| 1328 |
|
| 1329 |
|
| 1330 |
Other Documents |
| 1331 |
=============== |
| 1332 |
|
| 1333 |
.. toctree:: |
| 1334 |
:glob: |
| 1335 |
|
| 1336 |
self |
| 1337 |
Contributing <CONTRIBUTING> |
| 1338 |
News <NEWS> |
| 1339 |
|
| 1340 |
.. _timedelta: http://docs.python.org/3/library/datetime.html#timedelta-objects |