Python xml.etree.ElementTree.ParseError() Examples

The following are 30 code examples of xml.etree.ElementTree.ParseError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.etree.ElementTree , or try the search function .
Example #1
Source File: binding.py    From SA-ctf_scoreboard_admin with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #2
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def error(xml):
    """

    Test error handling.

    >>> issubclass(ET.ParseError, SyntaxError)
    True
    >>> error("foo").position
    (1, 0)
    >>> error("<tag>&foo;</tag>").position
    (1, 5)
    >>> error("foobar<").position
    (1, 6)

    """
    try:
        ET.XML(xml)
    except ET.ParseError:
        return sys.exc_value 
Example #3
Source File: decoding.py    From sentinelhub-py with MIT License 6 votes vote down vote up
def decode_sentinelhub_err_msg(response):
    """ Decodes error message from Sentinel Hub service

    :param response: Sentinel Hub service response
    :type response: requests.Response
    :return: An error message
    :rtype: str
    """
    try:
        server_message = []
        for elem in decode_data(response.content, MimeType.XML):
            if 'ServiceException' in elem.tag or 'Message' in elem.tag:
                server_message.append(elem.text.strip('\n\t '))
        return ''.join(server_message)
    except ElementTree.ParseError:
        return response.text 
Example #4
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def calendar_data(request):
    """
    AJAX JSON results for the calendar (rendered by dashboard.views.calendar)
    """
    try:
        st = iso8601.parse_date(request.GET['start'])
        en = iso8601.parse_date(request.GET['end'])
    except (KeyError, ValueError, iso8601.ParseError):
        return NotFoundResponse(request, errormsg="Bad request")

    user = get_object_or_404(Person, userid=request.user.username)
    local_tz = pytz.timezone(settings.TIME_ZONE)
    start = st - datetime.timedelta(days=1)
    end = en + datetime.timedelta(days=1)

    resp = HttpResponse(content_type="application/json")
    events = _calendar_event_data(user, start, end, local_tz, dt_string=True, colour=True,
            due_before=datetime.timedelta(minutes=1), due_after=datetime.timedelta(minutes=30))
    json.dump(list(events), resp, indent=1)
    return resp 
Example #5
Source File: alexaranking.py    From threat_intel with MIT License 6 votes vote down vote up
def _extract_response_xml(self, domain, response):
        """Extract XML content of an HTTP response into dictionary format.

        Args:
            response: HTML Response objects
        Returns:
            A dictionary: {alexa-ranking key : alexa-ranking value}.
        """
        attributes = {}
        alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
        try:
            xml_root = ET.fromstring(response._content)
            for xml_child in xml_root.findall('SD//'):
                if xml_child.tag in alexa_keys and \
                        alexa_keys[xml_child.tag] in xml_child.attrib:
                    attributes[xml_child.tag.lower(
                    )] = xml_child.attrib[alexa_keys[xml_child.tag]]
        except ParseError:
            # Skip ill-formatted XML and return no Alexa attributes
            pass
        attributes['domain'] = domain
        return {'attributes': attributes} 
Example #6
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #7
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #8
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = (response.body.read()).decode()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #9
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = (response.body.read()).decode()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #10
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def check_encoding(encoding):
    """
    >>> check_encoding("ascii")
    >>> check_encoding("us-ascii")
    >>> check_encoding("iso-8859-1")
    >>> check_encoding("iso-8859-15")
    >>> check_encoding("cp437")
    >>> check_encoding("mac-roman")
    >>> check_encoding("gbk")
    Traceback (most recent call last):
    ValueError: multi-byte encodings are not supported
    >>> check_encoding("cp037")
    Traceback (most recent call last):
    ParseError: unknown encoding: line 1, column 30
    """
    ET.XML("<?xml version='1.0' encoding='%s'?><xml />" % encoding) 
Example #11
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #12
Source File: sdp_scan.py    From bluescan with GNU General Public License v3.0 6 votes vote down vote up
def parse_sdptool_output(cls, output:str):
        '''Split the string output by sdptool into individual servcie records 
        and processes them separately.'''
        pattern = r'Failed to connect to SDP server on[\da-zA-Z :]*'
        pattern = re.compile(pattern)
        result = pattern.findall(output)
        for i in result:
            output = output.replace(i, '')

        record_xmls = output.split('<?xml version="1.0" encoding="UTF-8" ?>\n\n')[1:]
        print('Number of service records:', len(record_xmls), '\n\n')
        for record_xml in record_xmls:
            print(blue('Service Record'))
            try:
                sr = ServiceRecord(record_xml)
                sr.pp()
            except ElementTree.ParseError as e:
                print(record_xml)
            print('\n') 
Example #13
Source File: utils.py    From rucio with Apache License 2.0 6 votes vote down vote up
def parse_replicas_from_file(path):
    """
    Parses the output of list_replicas from a json or metalink file
    into a dictionary. Metalink parsing is tried first and if it fails
    it tries to parse json.

    :param path: the path to the input file

    :returns: a list with a dictionary for each file
    """
    with open(path) as fp:
        try:
            root = ElementTree.parse(fp).getroot()
            return parse_replicas_metalink(root)
        except ElementTree.ParseError as xml_err:
            try:
                return json.load(fp)
            except ValueError as json_err:
                raise MetalinkJsonParsingError(path, xml_err, json_err) 
Example #14
Source File: binding.py    From SplunkForPCAP with MIT License 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #15
Source File: helpers.py    From pytos with Apache License 2.0 6 votes vote down vote up
def read_ticket_info():
        """This function reads a SecureChange ticket_info from STDIN and returns a Ticket_Info object

        :return: The Ticket_Info object that was created from the XML input.
        :rtype: Secure_Change.XML_Objects.Secure_Change_API.Ticket_Info
        @raise ValueError if the XML string can not be parsed to a valid Ticket_Info object
        """
        ticket_info_xml_string = read_multiline_str_from_stdin()
        logger.debug("Got the following XML input:\n%s", ticket_info_xml_string)
        try:
            ticket_info_doc = ET.fromstring(ticket_info_xml_string)
        except ET.ParseError as parse_error:
            logger.error("Could not parse ticket info XML.")
            raise ValueError(parse_error)
        try:
            ticket_info = Ticket_Info(ticket_info_doc)
        except ValueError:
            message = "Got empty ticket info object, assuming test mode."
            logger.info(message)
            raise ValueError(message)
        except AttributeError:
            logger.error("Could not parse ticket_info XML.")
            raise AttributeError("Could not parse ticket_info XML.")
        return ticket_info 
Example #16
Source File: forecast.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def connect_to_catalog(self):
        self.catalog = TDSCatalog(self.catalog_url)
        self.fm_models = TDSCatalog(
            self.catalog.catalog_refs[self.model_type].href)
        self.fm_models_list = sorted(list(self.fm_models.catalog_refs.keys()))

        try:
            model_url = self.fm_models.catalog_refs[self.model_name].href
        except ParseError:
            raise ParseError(self.model_name + ' model may be unavailable.')

        try:
            self.model = TDSCatalog(model_url)
        except HTTPError:
            try:
                self.model = TDSCatalog(model_url)
            except HTTPError:
                raise HTTPError(self.model_name + ' model may be unavailable.')

        self.datasets_list = list(self.model.datasets.keys())
        self.set_dataset()
        self.connected = True 
Example #17
Source File: check_files.py    From addon-check with GNU General Public License v3.0 6 votes vote down vote up
def check_addon_xml(report: Report, addon_path: str, parsed_xml, folder_id_mismatch: bool):
    """Check whether the addon.xml present in the addon is parseable or not
        :addon_path: path to the addon
        :parsed_xml: parsed tree for xml file
        :folder_id_mismatch: whether to allow folder and id mismatch
    """
    addon_xml_path = os.path.join(addon_path, "addon.xml")
    try:
        handle_files.addon_file_exists(report, addon_path, r"addon\.xml")

        report.add(Record(INFORMATION, "Created by %s" %
                          parsed_xml.attrib.get("provider-name")))
        addon_xml_matches_folder(report, addon_path, parsed_xml, folder_id_mismatch)
    except ET.ParseError:
        report.add(Record(PROBLEM, "Addon xml not valid, check xml. %s" %
                          relative_path(addon_xml_path)))

    return parsed_xml 
Example #18
Source File: binding.py    From SplunkAdmins with Apache License 2.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #19
Source File: binding.py    From SplunkAdmins with Apache License 2.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #20
Source File: applekeychain.py    From pass-import with GNU General Public License v3.0 6 votes vote down vote up
def _decode_data(self, entry):
        """Decode data field (password or comments)."""
        key = entry.get('type', 'password')
        key = 'comments' if key == 'note' else key
        data = entry.pop('data', '')
        if isinstance(data, int):
            return key, ''

        data = self._decode(data)
        if key == 'comments':
            if data:
                try:
                    tree = ElementTree.XML(data)
                except ElementTree.ParseError:
                    return key, ''

                found = tree.find('.//string')
                if found is None:
                    return key, ''
                return key, found.text
            return key, ''
        return key, data 
Example #21
Source File: xfile.py    From document-api-python with MIT License 6 votes vote down vote up
def find_file_in_zip(zip_file):
    '''Returns the twb/tds file from a Tableau packaged file format. Packaged
    files can contain cache entries which are also valid XML, so only look for
    files with a .tds or .twb extension.
    '''

    candidate_files = filter(lambda x: x.split('.')[-1] in ('twb', 'tds'),
                             zip_file.namelist())

    for filename in candidate_files:
        with zip_file.open(filename) as xml_candidate:
            try:
                ET.parse(xml_candidate)
                return filename
            except ET.ParseError:
                # That's not an XML file by gosh
                pass 
Example #22
Source File: file_system_service.py    From python-devicecloud with Mozilla Public License 2.0 6 votes vote down vote up
def _parse_command_response(response):
    """Parse an SCI command response into ElementTree XML

    This is a helper method that takes a Requests Response object
    of an SCI command response and will parse it into an ElementTree Element
    representing the root of the XML response.

    :param response: The requests response object
    :return: An ElementTree Element that is the root of the response XML
    :raises ResponseParseError: If the response XML is not well formed
    """
    try:
        root = ET.fromstring(response.text)
    except ET.ParseError:
        raise ResponseParseError(
            "Unexpected response format, could not parse XML. Response: {}".format(response.text))

    return root 
Example #23
Source File: svn.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def _scanDir(self, workspace, dir, extra):
        self.__dir = dir
        try:
            info = ElementTree.fromstring(await check_output(
                ["svn", "info", "--xml", dir],
                cwd=workspace, universal_newlines=True))
            self.__url = info.find('entry/url').text
            self.__revision = int(info.find('entry').get('revision'))
            self.__repoRoot = info.find('entry/repository/root').text
            self.__repoUuid = info.find('entry/repository/uuid').text

            status = await check_output(["svn", "status", dir],
                cwd=workspace, universal_newlines=True)
            self.__dirty = status != ""
        except subprocess.CalledProcessError as e:
            raise BuildError("Svn audit failed: " + str(e))
        except OSError as e:
            raise BuildError("Error calling svn: " + str(e))
        except ElementTree.ParseError as e:
            raise BuildError("Invalid XML received from svn") 
Example #24
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def error(xml):
    """

    Test error handling.

    >>> issubclass(ET.ParseError, SyntaxError)
    True
    >>> error("foo").position
    (1, 0)
    >>> error("<tag>&foo;</tag>").position
    (1, 5)
    >>> error("foobar<").position
    (1, 6)

    """
    try:
        ET.XML(xml)
    except ET.ParseError:
        return sys.exc_value 
Example #25
Source File: __init__.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def parse_table_definition_file(file):
    """
    Read an parse the XML of a table-definition file.
    @return: an ElementTree object for the table definition
    """
    logging.info("Reading table definition from '%s'...", file)
    if not os.path.isfile(file):
        handle_error("File '%s' does not exist.", file)

    try:
        tableGenFile = ElementTree.ElementTree().parse(file)
    except OSError as e:
        handle_error("Could not read result file %s: %s", file, e)
    except ElementTree.ParseError as e:
        handle_error("Table file %s is invalid: %s", file, e)
    if "table" != tableGenFile.tag:
        handle_error(
            "Table file %s is invalid: It's root element is not named 'table'.", file
        )
    return tableGenFile 
Example #26
Source File: utils.py    From rucio with Apache License 2.0 6 votes vote down vote up
def parse_replicas_from_string(string):
    """
    Parses the output of list_replicas from a json or metalink string
    into a dictionary. Metalink parsing is tried first and if it fails
    it tries to parse json.

    :param string: the string to parse

    :returns: a list with a dictionary for each file
    """
    try:
        root = ElementTree.fromstring(string)
        return parse_replicas_metalink(root)
    except ElementTree.ParseError as xml_err:
        try:
            return json.loads(string)
        except ValueError as json_err:
            raise MetalinkJsonParsingError(string, xml_err, json_err) 
Example #27
Source File: pascal_voc.py    From ImageAI with MIT License 5 votes vote down vote up
def load_annotations(self, image_index):
        filename = self.image_names[image_index] + '.xml'
        try:
            tree = ET.parse(os.path.join(self.data_dir, 'Annotations', filename))
            return self.__parse_annotations(tree.getroot())
        except ET.ParseError as e:
            raise_from(ValueError('invalid annotations file: {}: {}'.format(filename, e)), None)
        except ValueError as e:
            raise_from(ValueError('invalid annotations file: {}: {}'.format(filename, e)), None) 
Example #28
Source File: test_database.py    From cantools with MIT License 5 votes vote down vote up
def test_jopp_5_0_sym(self):
        db = cantools.db.Database()

        with self.assertRaises(cantools.db.ParseError) as cm:
            db.add_sym_file('tests/files/sym/jopp-5.0.sym')

        self.assertEqual(str(cm.exception), 'Only SYM version 6.0 is supported.') 
Example #29
Source File: heal_libs.py    From glusto-tests with GNU General Public License v3.0 5 votes vote down vote up
def is_heal_disabled(mnode, volname):
    """Check if heal is disabled for a volume.

    Args:
        mnode : Node on which commands are executed
        volname : Name of the volume

    Returns:
        bool : True if heal is disabled on volume. False otherwise.
        NoneType: None if unable to get the volume status shd or parse error.
    """
    cmd = "gluster volume status %s shd --xml" % volname
    ret, out, _ = g.run(mnode, cmd, log_level='DEBUG')
    if ret != 0:
        g.log.error("Failed to get the self-heal-daemon status for the "
                    "volume" % volname)
        return None

    try:
        root = etree.XML(out)
    except etree.ParseError:
        g.log.error("Failed to parse the volume status shd xml output.")
        return None

    operr = root.find("opErrstr")
    if operr:
        if "Self-heal Daemon is disabled for volume" in operr.text:
            return True
    return False 
Example #30
Source File: main.py    From addon-check with GNU General Public License v3.0 5 votes vote down vote up
def _check_addon_xml(report: Report, addon_path):
    addon_xml_path = os.path.join(addon_path, "addon.xml")
    addon_xml = None
    try:
        _addon_file_exists(report, addon_path, r"addon\.xml")

        addon_xml = ET.parse(addon_xml_path)
        addon = addon_xml.getroot()
        report.add(Record(INFORMATION, "Created by %s" % addon.attrib.get("provider-name")))
        _addon_xml_matches_folder(report, addon_path, addon_xml)
    except ET.ParseError:
        report.add(Record(PROBLEM, "Addon xml not valid, check xml. %s" % relative_path(addon_xml_path)))

    return addon_xml