How to use the confuse.templates.Template function in confuse

To help you get started, we’ve selected a few confuse examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github beetbox / confuse / confuse / templates.py View on Github external
elif isinstance(value, set):
        # convert to list to avoid hash related problems
        return Choice(list(value))
    elif (SUPPORTS_ENUM and isinstance(value, type)
            and issubclass(value, enum.Enum)):
        return Choice(value)
    elif isinstance(value, list):
        return OneOf(value)
    elif value is float:
        return Number()
    elif isinstance(value, float):
        return Number(value)
    elif value is None:
        return Template(None)
    elif value is REQUIRED:
        return Template()
    elif value is dict:
        return TypeTemplate(abc.Mapping)
    elif value is list:
        return TypeTemplate(abc.Sequence)
    elif isinstance(value, type):
        return TypeTemplate(value)
    else:
        raise ValueError(u'cannot convert to template: {0!r}'.format(value))
github beetbox / confuse / confuse / templates.py View on Github external
Filenames are parsed equivalent to the `Filename` template and then
    converted to `pathlib.Path` objects.

    For Python 2 it returns the original path as returned by the `Filename`
    template.
    """
    def value(self, view, template=None):
        value = super(Path, self).value(view, template)
        if value is None:
            return
        import pathlib
        return pathlib.Path(value)


class TypeTemplate(Template):
    """A simple template that checks that a value is an instance of a
    desired Python type.
    """
    def __init__(self, typ, default=REQUIRED):
        """Create a template that checks that the value is an instance
        of `typ`.
        """
        super(TypeTemplate, self).__init__(default)
        self.typ = typ

    def convert(self, value, view):
        if not isinstance(value, self.typ):
            self.fail(
                u'must be a {0}, not {1}'.format(
                    self.typ.__name__,
                    type(value).__name__,
github beetbox / confuse / confuse / templates.py View on Github external
k, v = util.iter_first(x.items())
            elif isinstance(x, abc.Sequence):
                if len(x) != 2:
                    self.fail(u'must be a two-element list', view, True)
                k, v = x
            else:
                # Is this even possible? -> Likely, if some !directive cause
                # YAML to parse this to some custom type.
                self.fail(u'must be a single string, mapping, or a list'
                          u'' + str(x),
                          view, True)
            return (super(Pairs, self)._convert_value(k, view),
                    super(Pairs, self)._convert_value(v, view))


class Filename(Template):
    """A template that validates strings as filenames.

    Filenames are returned as absolute, tilde-free paths.

    Relative paths are relative to the template's `cwd` argument
    when it is specified, then the configuration directory (see
    the `config_dir` method) if they come from a file. Otherwise,
    they are relative to the current working directory. This helps
    attain the expected behavior when using command-line options.
    """
    def __init__(self, default=REQUIRED, cwd=None, relative_to=None,
                 in_app_dir=False):
        """`relative_to` is the name of a sibling value that is
        being validated at the same time.

        `in_app_dir` indicates whether the path should be resolved
github beetbox / confuse / confuse / templates.py View on Github external
elif isinstance(value, util.BASESTRING):
        return String(value)
    elif isinstance(value, set):
        # convert to list to avoid hash related problems
        return Choice(list(value))
    elif (SUPPORTS_ENUM and isinstance(value, type)
            and issubclass(value, enum.Enum)):
        return Choice(value)
    elif isinstance(value, list):
        return OneOf(value)
    elif value is float:
        return Number()
    elif isinstance(value, float):
        return Number(value)
    elif value is None:
        return Template(None)
    elif value is REQUIRED:
        return Template()
    elif value is dict:
        return TypeTemplate(abc.Mapping)
    elif value is list:
        return TypeTemplate(abc.Sequence)
    elif isinstance(value, type):
        return TypeTemplate(value)
    else:
        raise ValueError(u'cannot convert to template: {0!r}'.format(value))
github beetbox / confuse / confuse / templates.py View on Github external
self.subtemplates = subtemplates

    def value(self, view, template=None):
        """Get a dict with the same keys as the template and values
        validated according to the value types.
        """
        out = AttrDict()
        for key, typ in self.subtemplates.items():
            out[key] = typ.value(view[key], self)
        return out

    def __repr__(self):
        return 'MappingTemplate({0})'.format(repr(self.subtemplates))


class Sequence(Template):
    """A template used to validate lists of similar items,
    based on a given subtemplate.
    """
    def __init__(self, subtemplate):
        """Create a template for a list with items validated
        on a given subtemplate.
        """
        self.subtemplate = as_template(subtemplate)

    def value(self, view, template=None):
        """Get a list of items validated against the template.
        """
        out = []
        for item in view:
            out.append(self.subtemplate.value(item, self))
        return out