How to use the defusedxml.lxml function in defusedxml

To help you get started, we’ve selected a few defusedxml 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 GeoNode / geonode / geonode / monitoring / utils.py View on Github external
log.debug(" href: %s " % href)
        r = requests.get(
            href,
            auth=HTTPBasicAuth(username, password),
            timeout=30,
            verify=False)
        if r.status_code != 200:
            log.warning('Invalid response for %s: %s', href, r)
            return
        data = None
        try:
            data = r.json()
        except (ValueError, TypeError,):
            # traceback.print_exc()
            try:
                data = dlxml.fromstring(r.content)
            except Exception as err:
                log.debug("Cannot parse xml contents for %s: %s", href, err, exc_info=err)
                data = bs(r.content)
        if len(data) and format != 'json':
            return self.to_json(data, format)
        return data
github ReliaQualAssociates / ramstk / src / ramstk / gui / gtk / assistants / Preferences.py View on Github external
if _module == 'dfmeca':
            _fmt_path = "/root/tree[@name='DFMECA']/column"
        elif _module == 'ffmea':
            _fmt_path = "/root/tree[@name='FFMEA']/column"
        elif _module == 'hazops':
            _fmt_path = "/root/tree[@name='HazOps']/column"
        elif _module == 'pof':
            _fmt_path = "/root/tree[@name='PoF']/column"
        elif _module == 'similaritem':
            _fmt_path = "/root/tree[@name='SimilarItem']/column"
        else:
            _fmt_path = "/root/tree[@name='" + _module.title() + "']/column"

        # Retrieve the default heading text from the format file.
        _path = _fmt_path + '/defaulttitle'
        _default = lxml.parse(self._fmt_file).xpath(_path)

        # Retrieve the default heading text from the format file.
        _path = _fmt_path + '/usertitle'
        _user = lxml.parse(self._fmt_file).xpath(_path)

        # Retrieve the column position from the format file.
        _path = _fmt_path + '/position'
        _position = lxml.parse(self._fmt_file).xpath(_path)

        # Retrieve whether or not the column is editable from the format file.
        _path = _fmt_path + '/editable'
        _editable = lxml.parse(self._fmt_file).xpath(_path)

        # Retrieve whether or not the column is visible from the format file.
        _path = _fmt_path + '/visible'
        _visible = lxml.parse(self._fmt_file).xpath(_path)
github ReliaQualAssociates / ramstk / rtk / gui / gtk / Widgets.py View on Github external
:param int fmt_idx: the index of the format file to use when creating the
                        gtk.TreeView().
    :keyword str bg_col: the background color to use for each row.  Defaults to
                         white.
    :keyword str fg_col: the foreground (text) color to use for each row.
                         Defaults to black.
    :return: the gtk.TreeView() created by this method and the order of the
             gtk.TreeView() columns.
    :rtype: gtk.TreeView, list
    """
    # WARNING: Refactor make_treeview; current McCabe Complexity metric=21.
    from lxml import etree
    import defusedxml.lxml as lxml
    # Retrieve the column heading text from the format file.
    path = "/root/tree[@name='%s']/column/usertitle" % name
    heading = lxml.parse(fmt_file).xpath(path)

    # Retrieve the column datatype from the format file.
    path = "/root/tree[@name='%s']/column/datatype" % name
    datatype = etree.parse(fmt_file).xpath(path)

    # Retrieve the column position from the format file.
    path = "/root/tree[@name='%s']/column/position" % name
    position = etree.parse(fmt_file).xpath(path)

    # Retrieve the cell renderer type from the format file.
    path = "/root/tree[@name='%s']/column/widget" % name
    widget = etree.parse(fmt_file).xpath(path)

    # Retrieve whether or not the column is editable from the format file.
    path = "/root/tree[@name='%s']/column/editable" % name
    editable = etree.parse(fmt_file).xpath(path)
github googlefonts / fontbakery / deprecated / bakery_cli / utils.py View on Github external
def walk(self):
        l = len(self.upstream_path)
        exclude = ['build_info', ]
        for root, dirs, files in os_origin.walk(self.upstream_path, topdown=True):
            dirs[:] = [d for d in dirs if d not in exclude]
            for f in files:
                fullpath = op.join(root, f)

                if f[-4:].lower() == '.ttx':
                    try:
                        doc = defusedxml.lxml.parse(fullpath)
                        el = doc.xpath('//ttFont[@sfntVersion]')
                        if not el:
                            continue
                    except Exception as exc:
                        msg = 'Failed to parse "{}". Error: {}'
                        logger.error(msg.format(fullpath, exc))
                        continue
                    self.TTX.append(fullpath[l:].strip('/'))

                if op.basename(f).lower() == 'metadata.pb':
                    self.METADATA.append(fullpath[l:].strip('/'))

                if f[-4:].lower() in ['.ttf', '.otf']:
                    self.BIN.append(fullpath[l:].strip('/'))

                if f[-4:].lower() == '.sfd':
github dimagi / commcare-hq / corehq / apps / api / serializers.py View on Github external
def case_to_etree(self, case):
        '''
        Encapsulates the version passed to `CommCareCase.to_xml` and
        the temporary hack of re-parsing it. TODO: expose a direct etree
        encoding in casexml?
        '''
        return lxml.parse(BytesIO(case.to_xml('2.0', include_case_on_closed=True))).getroot()
github kibitzr / kibitzr / kibitzr / transformer / xpath.py View on Github external
if isinstance(xpath_results, list):
        if select_all is False:
            xpath_results = xpath_results[0:1]
    else:
        xpath_results = [xpath_results]

    results = []
    for r in xpath_results:
        # namespace declarations
        if isinstance(r, tuple):
            results.append("%s=\"%s\"" % (r[0], r[1]))
        # an element
        elif hasattr(r, 'tag'):
            results.append(
                re.sub(r'\s+', ' ',
                       dlxml.tostring(r, method='html', encoding='unicode'))
            )
        else:
            results.append(r)

    return u"\n".join(six.text_type(x).strip() for x in results)
github kibitzr / kibitzr / kibitzr / transformer / xpath.py View on Github external
def parse_html(html):
    """
    Returns `html` parsed with lxml.

    :param html: Unicode content
    """
    from defusedxml import lxml as dlxml
    from lxml import etree

    # lxml requires argument to be bytes
    # see https://github.com/kibitzr/kibitzr/issues/47
    encoded = html.encode('utf-8')
    return dlxml.fromstring(encoded, parser=etree.HTMLParser())
github tysonclugg / rinse / rinse / util.py View on Github external
def safe_parse_path(xml_path, **kwargs):
    """Safely parse XML content from path into an element tree."""
    return defusedxml.lxml.parse(xml_path, **kwargs)
github greenbone / gvm-tools / gmp / xml.py View on Github external
def append_xml_str(self, xml_text):
        """Append a xml element in string format."""
        node = secET.fromstring(xml_text)
        self._element.append(node)