anyconfig.backend.xml

XML backend:

  • Format to support: XML, e.g. http://www.w3.org/TR/xml11/
  • Requirements: one of the followings
    • xml.etree.cElementTree in standard lib if python >= 2.5
    • xml.etree.ElementTree in standard lib if python >= 2.5
    • elementtree.ElementTree (otherwise)
  • Development Status :: 4 - Beta
  • Limitations:
    • special node '@attrs‘, '@text‘ and '@children‘ are used to keep XML structure of original data. You have to cusomize them with ‘tags’ keyword option to avoid any config parameters conflict with some of them.
    • Some data or structures of original XML file may be lost if make it backed to XML file; XML file - (anyconfig.load) -> config - (anyconfig.dump) -> XML file
    • XML specific features (namespace, etc.) may not be processed correctly.
  • Special Options:
    • ac_parse_value: Try to parse values, elements’ text and attributes.
    • merge_attrs: Merge attributes and mix with children nodes. Please note that information of attributes are lost after load if this option is used.
    • tags: A dict provide special parameter names to distinguish between attributes, text and children nodes. Default is {“attrs”: “@attrs”, “text”: “@text”, “children”: “@children”}.

Changelog:

    Changed in version 0.8.2:
  • Add special options, tags, merge_attrs and ac_parse_value

  • Remove special option, pprefix which conflicts with another option tags

    Changed in version 0.8.0:
  • Try to make a nested dict w/o extra dict having keys of attrs, text and children from XML string/file as much as possible.

  • Support namespaces partially.

    Changed in version 0.1.0:
  • Added XML dump support.

anyconfig.backend.xml._iterparse(xmlfile)

Avoid bug in python 3.{2,3}. See http://bugs.python.org/issue9257.

Parameters:xmlfile – XML file or file-like object
anyconfig.backend.xml.flip(tpl)
>>> flip((1, 2))
(2, 1)
anyconfig.backend.xml._namespaces_from_file(xmlfile)
Parameters:xmlfile – XML file or file-like object
Returns:{namespace_uri: namespace_prefix} or {}
anyconfig.backend.xml._tweak_ns(tag, **options)
Parameters:
  • tag – XML tag element
  • nspaces – A namespaces dict, {uri: prefix}
  • options – Extra keyword options may contain ‘nspaces’ keyword option provide a namespace dict, {uri: prefix}
>>> _tweak_ns("a", nspaces={})
'a'
>>> _tweak_ns("a", nspaces={"http://example.com/ns/val/": "val"})
'a'
>>> _tweak_ns("{http://example.com/ns/val/}a",
...           nspaces={"http://example.com/ns/val/": "val"})
'val:a'
anyconfig.backend.xml._dicts_have_unique_keys(dics)
Parameters:dics – [<dict or dict-like object>], must not be [] or [{...}]
Returns:True if all keys of each dict of dics are unique

# Enable the followings if to allow dics is [], [{...}]: # >>> all(_dicts_have_unique_keys([d]) for [d] # ... in ({}, {‘a’: 0}, {‘a’: 1, ‘b’: 0})) # True # >>> _dicts_have_unique_keys([{}, {‘a’: 1}, {‘b’: 2, ‘c’: 0}]) # True

>>> _dicts_have_unique_keys([{}, {'a': 1}, {'a': 2}])
False
>>> _dicts_have_unique_keys([{}, {'a': 1}, {'b': 2}, {'b': 3, 'c': 0}])
False
>>> _dicts_have_unique_keys([{}, {}])
True
anyconfig.backend.xml._merge_dicts(dics, container=<type 'dict'>)
Parameters:
  • dics – [<dict/-like object must not have same keys each other>]
  • container – callble to make a container object
Returns:

<container> object

>>> _merge_dicts(({}, ))
{}
>>> _merge_dicts(({'a': 1}, ))
{'a': 1}
>>> sorted(kv for kv in _merge_dicts(({'a': 1}, {'b': 2})).items())
[('a', 1), ('b', 2)]
anyconfig.backend.xml._parse_text(val, **options)
Returns:Parsed value or value itself depends on ac_parse_value
anyconfig.backend.xml._process_elem_text(elem, dic, subdic, text='@text', **options)
Parameters:
  • elem – ET Element object which has elem.text
  • dic – <container> (dict[-like]) object converted from elem
  • subdic – Sub <container> object converted from elem
  • options – Keyword options, see the description of elem_to_container() for more details.
Returns:

None but updating elem.text, dic and subdic as side effects

anyconfig.backend.xml._parse_attrs(elem, container=<type 'dict'>, **options)
Parameters:
  • elem – ET Element object has attributes (elem.attrib)
  • container – callble to make a container object
Returns:

Parsed value or value itself depends on ac_parse_value

anyconfig.backend.xml._process_elem_attrs(elem, dic, subdic, container=<type 'dict'>, attrs='@attrs', **options)
Parameters:
  • elem – ET Element object or None
  • dic – <container> (dict[-like]) object converted from elem
  • subdic – Sub <container> object converted from elem
  • options – Keyword options, see the description of elem_to_container() for more details.
Returns:

None but updating dic and subdic as side effects

anyconfig.backend.xml._process_children_elems(elem, dic, subdic, container=<type 'dict'>, children='@children', **options)
Parameters:
  • elem – ET Element object or None
  • dic – <container> (dict[-like]) object converted from elem
  • subdic – Sub <container> object converted from elem
  • container – callble to make a container object
  • children – Tag for children nodes
  • options – Keyword options, see the description of elem_to_container() for more details.
Returns:

None but updating dic and subdic as side effects

anyconfig.backend.xml.elem_to_container(elem, container=<type 'dict'>, **options)

Convert XML ElementTree Element to a collection of container objects.

Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience.

  • There is only text element
  • There are only children elements each has unique keys among all
Parameters:
  • elem – ET Element object or None
  • container – callble to make a container object
  • options

    Keyword options

    • nspaces: A namespaces dict, {uri: prefix} or None
    • attrs, text, children: Tags for special nodes to keep XML info
    • merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation.
anyconfig.backend.xml._complement_tag_options(options)
Parameters:options – Keyword options :: dict
>>> ref = _TAGS.copy()
>>> ref["text"] = "#text"
>>> opts = _complement_tag_options({"tags": {"text": ref["text"]}})
>>> del opts["tags"]  # To simplify comparison.
>>> sorted(opts.items())
[('attrs', '@attrs'), ('children', '@children'), ('text', '#text')]
anyconfig.backend.xml.root_to_container(root, container=<type 'dict'>, nspaces=None, **options)

Convert XML ElementTree Root Element to a collection of container objects.

Parameters:
  • root – etree root object or None
  • container – callble to make a container object
  • nspaces – A namespaces dict, {uri: prefix} or None
  • options

    Keyword options,

    • tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {“attrs”: “@attrs”, “text”: “#text”}
anyconfig.backend.xml._to_str_fn(**options)
Parameters:
  • options – Keyword options might have ‘ac_parse_value’ key
  • to_str – Callable to convert value to string
anyconfig.backend.xml._elem_set_attrs(obj, parent, to_str)
Parameters:
  • obj – Container instance gives attributes of XML Element
  • parent – XML ElementTree parent node object
  • to_str – Callable to convert value to string or None
  • options – Keyword options, see container_to_etree()
Returns:

None but parent will be modified

anyconfig.backend.xml._elem_from_descendants(children_nodes, **options)
Parameters:
  • children_nodes – A list of child dict objects
  • options – Keyword options, see container_to_etree()
anyconfig.backend.xml._get_or_update_parent(key, val, to_str, parent=None, **options)
Parameters:
  • key – Key of current child (dict{,-like} object)
  • val – Value of current child (dict{,-like} object or [dict{,...}])
  • to_str – Callable to convert value to string
  • parent – XML ElementTree parent node object or None
  • options – Keyword options, see container_to_etree()
anyconfig.backend.xml.container_to_etree(obj, parent=None, to_str=None, **options)

Convert a dict-like object to XML ElementTree.

Parameters:
  • obj – Container instance to convert to
  • parent – XML ElementTree parent node object or None
  • to_str – Callable to convert value to string or None
  • options

    Keyword options,

    • tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {“attrs”: “@attrs”, “text”: “#text”}
anyconfig.backend.xml.etree_write(tree, stream)

Write XML ElementTree root content into stream.

Parameters:
  • tree – XML ElementTree object
  • stream – File or file-like object can write to
class anyconfig.backend.xml.Parser

Bases: anyconfig.backend.base.Parser, anyconfig.backend.base.ToStreamDumperMixin, anyconfig.backend.base.BinaryFilesMixin

Parser for XML files.

_type = 'xml'
_extensions = ['xml']
_load_opts = ['tags', 'merge_attrs', 'ac_parse_value']
_dump_opts = ['tags', 'merge_attrs', 'ac_parse_value']
_ordered = True
_dict_opts = ['ac_dict']
load_from_string(content, container, **opts)

Load config from XML snippet (a string content).

Parameters:
  • content – XML snippet string of str (python 2) or bytes (python 3) type
  • container – callble to make a container object
  • opts – optional keyword parameters passed to
Returns:

Dict-like object holding config parameters

load_from_path(filepath, container, **opts)
Parameters:
  • filepath – XML file path
  • container – callble to make a container object
  • opts – optional keyword parameters to be sanitized
Returns:

Dict-like object holding config parameters

load_from_stream(stream, container, **opts)
Parameters:
  • stream – XML file or file-like object
  • container – callble to make a container object
  • opts – optional keyword parameters to be sanitized
Returns:

Dict-like object holding config parameters

dump_to_string(cnf, **opts)
Parameters:
  • cnf – Configuration data to dump
  • opts – optional keyword parameters
Returns:

string represents the configuration

dump_to_stream(cnf, stream, **opts)
Parameters:
  • cnf – Configuration data to dump
  • stream – Config file or file like object write to
  • opts – optional keyword parameters
__module__ = 'anyconfig.backend.xml'