How to use the xmlschema.resources.XMLResource function in xmlschema

To help you get started, we’ve selected a few xmlschema 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 sissaschool / xmlschema / xmlschema / resources.py View on Github external
def fetch_namespaces(source, base_url=None, defuse='remote', timeout=30):
    """
    Fetches namespaces information from the XML data source. The argument *source*
    can be a string containing the XML document or file path or an url or a file-like
    object or an ElementTree instance or an Element instance. A dictionary with
    namespace mappings is returned.
    """
    resource = XMLResource(source, base_url, defuse, timeout)
    return resource.get_namespaces()
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
:param fill_missing: if set to `True` the decoder fills also missing attributes. \
        The filling value is `None` or a typed value if the *filler* callback is provided.
        :param max_depth: maximum level of decoding, for default there is no limit.
        :param kwargs: keyword arguments with other options for converter and decoder.
        :return: yields a decoded data object, eventually preceded by a sequence of validation \
        or decoding errors.
        """
        if not self.built:
            if self.meta_schema is not None:
                raise XMLSchemaNotBuiltError(self, "schema %r is not built" % self)
            self.build()

        if validation not in XSD_VALIDATION_MODES:
            raise XMLSchemaValueError("validation argument can be 'strict', 'lax' or 'skip': %r" % validation)
        elif not isinstance(source, XMLResource):
            source = XMLResource(source, defuse=self.defuse, timeout=self.timeout, lazy=False)

        if not schema_path and path:
            schema_path = path if path.startswith('/') else '/%s/%s' % (source.root.tag, path)

        if process_namespaces:
            root_only = source.is_lazy() and not namespaces
            namespaces = source.get_namespaces(namespaces, root_only)
            namespace = source.namespace or namespaces.get('', '')
        else:
            root_only = namespaces = None
            namespace = source.namespace

        try:
            schema = self.maps.namespaces[namespace][0]
        except (KeyError, IndexError):
            reason = 'the namespace {!r} is not loaded'.format(namespace)
github sissaschool / xmlschema / xmlschema / resources.py View on Github external
Fetches schema location hints from an XML data source and a list of location hints.
    If an accessible schema location is not found raises a ValueError.

    :param source: can be an :class:`XMLResource` instance, a file-like object a path \
    to a file or an URI of a resource or an Element instance or an ElementTree instance or \
    a string containing the XML data. If the passed argument is not an :class:`XMLResource` \
    instance a new one is built using this and *defuse*, *timeout* and *lazy* arguments.
    :param locations: a dictionary or dictionary items with additional schema location hints.
    :param base_url: the same argument of the :class:`XMLResource`.
    :param defuse: the same argument of the :class:`XMLResource`.
    :param timeout: the same argument of the :class:`XMLResource` but with a reduced default.
    :return: A 2-tuple with the URL referring to the first reachable schema resource \
    and a list of dictionary items with normalized location hints.
    """
    if not isinstance(source, XMLResource):
        resource = XMLResource(source, base_url, defuse, timeout)
    else:
        resource = source

    base_url = resource.base_url
    namespace = resource.namespace
    locations = resource.get_locations(locations)
    if not locations:
        msg = "the XML data resource {!r} does not contain any schema location hint."
        raise XMLSchemaValueError(msg.format(source))

    for ns, url in sorted(locations, key=lambda x: x[0] != namespace):
        try:
            return fetch_resource(url, base_url, timeout), locations
        except XMLSchemaURLError:
            pass

github sissaschool / xmlschema / xmlschema / resources.py View on Github external
Load XML data source into an Element tree, returning the root Element, the XML text and an
    url, if available. Usable for XML data files of small or medium sizes, as XSD schemas.
    This helper function is deprecated from v1.0.17, use :class:`XMLResource` instead.

    :param source: an URL, a filename path or a file-like object.
    :param element_only: if True the function returns only the root Element of the tree.
    :param resource_options: keyword arguments for providing :class:`XMLResource` init options.
    :return: a tuple with three items (root Element, XML text and XML URL) or \
    only the root Element if 'element_only' argument is True.
    """
    import warnings
    warnings.warn("load_xml_resource() function will be removed in 1.1 version",
                  DeprecationWarning, stacklevel=2)

    lazy = resource_options.pop('lazy', False)
    source = XMLResource(source, lazy=lazy, **resource_options)
    if element_only:
        return source.root
    else:
        source.load()
        return source.root, source.text, source.url

github sissaschool / xmlschema / xmlschema / resources.py View on Github external
"""
    Fetches schema location hints from an XML data source and a list of location hints.
    If an accessible schema location is not found raises a ValueError.

    :param source: can be an :class:`XMLResource` instance, a file-like object a path \
    to a file or an URI of a resource or an Element instance or an ElementTree instance or \
    a string containing the XML data. If the passed argument is not an :class:`XMLResource` \
    instance a new one is built using this and *defuse*, *timeout* and *lazy* arguments.
    :param locations: a dictionary or dictionary items with additional schema location hints.
    :param base_url: the same argument of the :class:`XMLResource`.
    :param defuse: the same argument of the :class:`XMLResource`.
    :param timeout: the same argument of the :class:`XMLResource` but with a reduced default.
    :return: A 2-tuple with the URL referring to the first reachable schema resource \
    and a list of dictionary items with normalized location hints.
    """
    if not isinstance(source, XMLResource):
        resource = XMLResource(source, base_url, defuse, timeout)
    else:
        resource = source

    base_url = resource.base_url
    namespace = resource.namespace
    locations = resource.get_locations(locations)
    if not locations:
        msg = "the XML data resource {!r} does not contain any schema location hint."
        raise XMLSchemaValueError(msg.format(source))

    for ns, url in sorted(locations, key=lambda x: x[0] != namespace):
        try:
            return fetch_resource(url, base_url, timeout), locations
        except XMLSchemaURLError:
            pass
github sissaschool / xmlschema / xmlschema / documents.py View on Github external
if cls is None:
        cls = XMLSchema

    try:
        schema, locations = fetch_schema_locations(source, locations, base_url=base_url)
    except ValueError:
        if schema is None:
            raise
        elif not isinstance(schema, XMLSchemaBase):
            schema = cls(schema, validation='strict', locations=locations, base_url=base_url,
                         defuse=defuse, timeout=timeout)
    else:
        schema = cls(schema, validation='strict', locations=locations, defuse=defuse, timeout=timeout)

    if not isinstance(source, XMLResource):
        source = XMLResource(source, defuse=defuse, timeout=timeout, lazy=lazy)

    return source, schema
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
path to a file or an URI of a resource or an opened file-like object or an Element \
        instance or an ElementTree instance or a string containing the XML data.
        :param path: is an optional XPath expression that matches the elements of the XML \
        data that have to be decoded. If not provided the XML root element is selected.
        :param schema_path: an alternative XPath expression to select the XSD element to use for \
        decoding. Useful if the root of the XML data doesn't match an XSD global element of the schema.
        :param use_defaults: Use schema's default values for filling missing data.
        :param namespaces: is an optional mapping from namespace prefix to URI.
        """
        if not self.built:
            if self.meta_schema is not None:
                raise XMLSchemaNotBuiltError(self, "schema %r is not built" % self)
            self.build()

        if not isinstance(source, XMLResource):
            source = XMLResource(source, defuse=self.defuse, timeout=self.timeout, lazy=False)
        if not schema_path and path:
            schema_path = path if path.startswith('/') else '/%s/%s' % (source.root.tag, path)

        id_map = Counter()
        root_only = source.is_lazy() and not namespaces
        namespaces = source.get_namespaces(namespaces, root_only)
        namespace = source.namespace or namespaces.get('', '')

        try:
            schema = self.maps.namespaces[namespace][0]
        except (KeyError, IndexError):
            reason = 'the namespace {!r} is not loaded'.format(namespace)
            yield self.validation_error('lax', reason, source.root, source, namespaces)
            return

        kwargs = {
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
def __init__(self, source, namespace=None, validation='strict', global_maps=None,
                 converter=None, locations=None, base_url=None, defuse='remote',
                 timeout=300, build=True, use_meta=True, loglevel=None):
        super(XMLSchemaBase, self).__init__(validation)
        ElementPathMixin.__init__(self)

        if loglevel is not None:
            logger.setLevel(loglevel)
        elif build and global_maps is None:
            logger.setLevel(logging.WARNING)

        self.source = XMLResource(source, base_url, defuse, timeout, lazy=False)
        logger.debug("Read schema from %r", self.source)

        self.imports = {}
        self.includes = {}
        self.warnings = []
        self._root_elements = None
        root = self.source.root

        # Parse namespaces and targetNamespace
        self.namespaces = self.source.get_namespaces(
            namespaces={'xml': XML_NAMESPACE}  # the XML namespace is implicitly declared
        )
        try:
            self.target_namespace = root.attrib['targetNamespace']
        except KeyError:
            pass