plainbox.impl.config – configuration

Warning

THIS MODULE DOES NOT HAVE A STABLE PUBLIC API

class plainbox.impl.secure.config.ChoiceValidator(choice_list)[source]

Bases: plainbox.impl.secure.config.IValidator

A validator ensuring that values are in a given set

class plainbox.impl.secure.config.Config[source]

Bases: object

Base class for configuration systems

Attr _var:storage backend for Variable definitions
Attr _section:storage backend for Section definitions
Attr _filename_list:
 list of pathnames to files that were loaded by the last call to read()
Attr _problem_list:
 list of ValidationError that were detected by the last call to read()
class Meta

Bases: plainbox.impl.secure.config.ConfigMetaData

filename_list = []
parametric_section_list = []
section_list = []
variable_list = []
Config.filename_list

list of pathnames to files that were loaded by the last call to read()

classmethod Config.get()[source]

Get an instance of this Config class with all the configuration loaded from default locations. The locations are determined by Meta.filename_list attribute.

Returns:fresh Config instance
Config.get_parser_obj()[source]

Get a ConfigParser-like object with the same data.

Returns:A PlainBoxConfigParser object with all of the data copied from this Config object.

Since PlainBoxConfigParser is a subclass of configparser.ConfigParser it has a number of useful utility methods. By using this function one can obtain a ConfigParser-like object and work with it directly.

Config.problem_list

list of ValidationError that were detected by the last call to read()

Config.read(filename_list)[source]

Load and merge settings from many files.

This method tries to open each file from the list of filenames, parse it as an INI file using PlainBoxConfigParser (a simple ConfigParser subclass that respects the case of key names). The list of files actually accessed is saved as available as Config.filename_list.

If any problem is detected during parsing (e.g. syntax errors) those are captured and added to the Config.problem_list.

After all files are loaded each Variable and Section defined in the Config class is assigned with the data from the merged configuration data.

Any variables that cannot be assigned and raise ValidationError are ignored but the list of problems is saved.

All unused configuration (extra variables that are not defined as either Variable or Section class) is silently ignored.

Note

This method resets _problem_list and _filename_list.

Config.read_string(string)[source]

Load settings from a string.

Parameters:string – The full text of INI-like configuration to parse and apply

This method parses the string as an INI file using PlainBoxConfigParser (a simple ConfigParser subclass that respects the case of key names).

If any problem is detected during parsing (e.g. syntax errors) those are captured and added to the Config.problem_list.

After parsing the string each Variable and Section defined in the Config class is assigned with the data from the configuration data.

Any variables that cannot be assigned and raise ValidationError are ignored but the list of problems is saved.

All unused configuration (extra variables that are not defined as either Variable or Section class) is silently ignored.

Note

This method resets _problem_list and _filename_list.

Config.validate_whole()[source]

Validate the whole configuration object.

This method may be overridden to provide whole-configuration validation. It is especially useful in cases when a pair or more of variables need to be validated together to be meaningful.

The default implementation does nothing. Other implementations may raise ValidationError.

Config.write(stream)[source]

Write configuration data to a stream.

Parameters:stream – a file-like object that can be written to.

This method recreates the content of all the configuration variables in a manner that can be subsequently read back.

class plainbox.impl.secure.config.ConfigMeta[source]

Bases: type

Meta class for all configuration classes.

This meta class handles assignment of ‘_name’ attribute to each Variable instance created in the class body.

It also accumulates such instances and assigns them to variable_list in a helper Meta class which is assigned back to the namespace

mro() → list

return a type’s method resolution order

class plainbox.impl.secure.config.ConfigMetaData[source]

Bases: object

Class containing meta-data about a Config class

Sub-classes of this class are automatically added to each Config subclass as a Meta class-level attribute.

This class has typically two attributes:

Attr variable_list:
 A list of all Variable objects defined in the class
Attr section_list:
 A list of all Section object defined in the class
Attr filename_list:
 A list of config files (pathnames) to read on call to Config.read()
filename_list = []
parametric_section_list = []
section_list = []
variable_list = []
class plainbox.impl.secure.config.INameTracking[source]

Bases: object

Interface for classes that are instantiated as a part of definition of another class. The purpose of this interface is to allow instances to learn about the name (python identifier) that was assigned to the instance at class definition time.

Subclasses must define the _set_tracked_name() method.

class plainbox.impl.secure.config.IValidator[source]

Bases: object

An interface for variable vale validators

plainbox.impl.secure.config.KindValidator(variable, new_value)[source]

A validator ensuring that values match the “kind” of the variable.

class plainbox.impl.secure.config.NotEmptyValidator(msg=None)[source]

Bases: plainbox.impl.secure.config.IValidator

A validator ensuring that values aren’t empty

class plainbox.impl.secure.config.NotUnsetValidator(msg=None)[source]

Bases: plainbox.impl.secure.config.IValidator

A validator ensuring that values are set

..note::
Due to the way validators work this validator must be the first one in any validator list in order to work. Otherwise the implicit KindValidator() will take precedence and the check will most likely fail as None or Unset are not of the expected type of the configuration variable being worked with.
understands_Unset = True
class plainbox.impl.secure.config.ParametricSection(name=None, *, help_text=None)[source]

Bases: plainbox.impl.secure.config.Section

A parametrized section of a configuration file.

This is similar to Section, but instead looks for an arbitrary number of sections beginning with name:. E.g.:

[foo:bar]
    somevar = someval
[foo:baz]
    othervar = otherval

yields a following list of dictionaries:

[
    {'bar': {'somevar': 'someval'}},
    {'baz': {'othervar': 'otherval'}}
]
help_text

an optional help text associated with this section

name

name of this section

class plainbox.impl.secure.config.PatternValidator(pattern_text)[source]

Bases: plainbox.impl.secure.config.IValidator

A validator ensuring that values match a given pattern

class plainbox.impl.secure.config.PlainBoxConfigParser(defaults=None, dict_type=<class 'collections.OrderedDict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)[source]

Bases: configparser.ConfigParser

A subclass of ConfigParser with the following changes:

  • option names are not lower-cased
  • write() has deterministic ordering (sorted by name)
  • parsing list capability
BOOLEAN_STATES = {'off': False, 'no': False, 'true': True, 'on': True, 'false': False, '1': True, 'yes': True, '0': False}
NONSPACECRE = re.compile('\\S')
OPTCRE = re.compile('\n (?P<option>.*?) # very permissive!\n \\s*(?P<vi>=|:)\\s* # any number of space/tab,\n # followed by any of t, re.VERBOSE)
OPTCRE_NV = re.compile('\n (?P<option>.*?) # very permissive!\n \\s*(?: # any number of space/tab,\n (?P<vi>=|:)\\s* # optionally followed , re.VERBOSE)
SECTCRE = re.compile('\n \\[ # [\n (?P<header>[^]]+) # very permissive!\n \\] # ]\n ', re.VERBOSE)
add_section(section)

Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.

clear() → None. Remove all items from D.
converters
defaults()
get(section, option, *, raw=False, vars=None, fallback=<object object>)

Get an option value for a given section.

If `vars’ is provided, it must be a dictionary. The option is looked up in `vars’ (if provided), `section’, and in `DEFAULTSECT’ in that order. If the key is not found and `fallback’ is provided, it is used as a fallback value. `None’ can be provided as a `fallback’ value.

If interpolation is enabled and the optional argument `raw’ is False, all interpolations are expanded in the return values.

Arguments `raw’, `vars’, and `fallback’ are keyword only.

The section DEFAULT is special.

getboolean(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)
getfloat(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)
getint(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)
getlist(section, option, *, raw=False, vars=None, fallback=<object object>, **kwargs)[source]
has_option(section, option)

Check for the existence of a given option in a given section. If the specified `section’ is None or an empty string, DEFAULT is assumed. If the specified `section’ does not exist, returns False.

has_section(section)

Indicate whether the named section is present in the configuration.

The DEFAULT section is not acknowledged.

items(section=<object object>, raw=False, vars=None)

Return a list of (name, value) tuples for each option in a section.

All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw’ is true. Additional substitutions may be provided using the `vars’ argument, which must be a dictionary whose contents overrides any pre-existing defaults.

The section DEFAULT is special.

keys() → a set-like object providing a view on D's keys
options(section)

Return a list of option names for the given section name.

optionxform(option)[source]

Overridden method from configparser.ConfigParser.

Returns option without any transformations

pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

Remove a section from the parser and return it as a (section_name, section_proxy) tuple. If no section is present, raise KeyError.

The section DEFAULT is never returned because it cannot be removed.

read(filenames, encoding=None)

Read and parse a filename or a list of filenames.

Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user’s home directory, systemwide directory), and all existing configuration files in the list will be read. A single filename may also be given.

Return list of successfully read files.

read_dict(dictionary, source='<dict>')

Read configuration from a dictionary.

Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order.

All types held in the dictionary are converted to strings during reading, including section names, option names and keys.

Optional second argument is the `source’ specifying the name of the dictionary being read.

read_file(f, source=None)

Like read() but the argument must be a file-like object.

The `f’ argument must be iterable, returning one line at a time. Optional second argument is the `source’ specifying the name of the file being read. If not given, it is taken from f.name. If `f’ has no `name’ attribute, `<???>’ is used.

read_string(string, source='<string>')

Read configuration from a given string.

readfp(fp, filename=None)

Deprecated, use read_file instead.

remove_option(section, option)

Remove an option.

remove_section(section)

Remove a file section.

sections()

Return a list of section names, excluding [DEFAULT]

set(section, option, value=None)

Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) → None. Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() → an object providing a view on D's values
write(fp, space_around_delimiters=True)[source]

Write an .ini-format representation of the configuration state.

If space_around_delimiters is True (the default), delimiters between keys and values are surrounded by spaces. The ordering of section and values within is deterministic.

class plainbox.impl.secure.config.Section(name=None, *, help_text=None)[source]

Bases: plainbox.impl.secure.config.INameTracking

A section of a configuration file.

help_text

an optional help text associated with this section

name

name of this section

class plainbox.impl.secure.config.SubsetValidator(superset)[source]

Bases: plainbox.impl.secure.config.IValidator

A validator ensuring that value is a subset of a given set.

class plainbox.impl.secure.config.UnsetType[source]

Bases: object

Class of the Unset object

exception plainbox.impl.secure.config.ValidationError(variable, new_value, message)[source]

Bases: ValueError

Exception raised when configuration variables fail to validate

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class plainbox.impl.secure.config.Variable(name=None, *, section='DEFAULT', kind=<class 'str'>, default=Unset, validator_list=None, help_text=None)[source]

Bases: plainbox.impl.secure.config.INameTracking

Variable that can be used in a configuration systems

default

a default value, if any

help_text

an optional help text associated with this variable

kind

the “poor man’s type”, can be only str (default), bool, float or int

mangled_name

name prefixed by the name of the section name and ‘__’ to resolve conflicts between same name variables living in different sections

name

name of this variable

section

name of the section this variable belongs to (in a configuration file)

validate(value)[source]

Check if the supplied value is valid for this variable.

Parameters:value – The proposed value
Raises:ValidationError – If the value was not valid in any way
validator_list

a optional list of Validator instances that are enforced on the value

plainbox.impl.secure.config.understands_Unset(cls_or_func)[source]

Decorator for marking validators as supporting the special Unset value.

This decorator should be applied to every validator that natively supports Unset values. Without it, Unset is never validated.

This decorator works by setting the understands_Unset attribute on the decorated object and returning it intact.

comments powered by Disqus