Python xml.sax.saxutils.escape() Examples

The following are 30 code examples of xml.sax.saxutils.escape(). 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.sax.saxutils , or try the search function .
Example #1
Source File: Feed.py    From python-in-practice with GNU General Public License v3.0 8 votes vote down vote up
def _parse(data, limit):
        output = []
        feed = feedparser.parse(data) # Atom + RSS
        for entry in feed["entries"]:
            title = entry.get("title")
            link = entry.get("link")
            if title:
                if link:
                    output.append('<li><a href="{}">{}</a></li>'.format(
                            link, escape(title)))
                else:
                    output.append('<li>{}</li>'.format(escape(title)))
            if limit and len(output) == limit:
                break
        if output:
            return ["<ul>"] + output + ["</ul>"] 
Example #2
Source File: sanitizer.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #3
Source File: sanitizer.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #4
Source File: sanitizer.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #5
Source File: importxml.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
def _set_date_to_xml_text(self, date_value, date_error, xml_element_name, xml_attrs):
        """
        Common handling of invalid dates for the date... element handlers.

        Prints warning on console and sets date_value to a text-only date
        with the problematic XML inside.
        """
        xml = "<{element_name} {attrs}/>".format(
            element_name = xml_element_name,
            attrs = " ".join(
                ['{}="{}"'.format(k,escape(v, entities={'"' : "&quot;"}))
                    for k,v in xml_attrs.items()]))
        # TRANSLATORS: leave the {date} and {xml} untranslated in the format string,
        # but you may re-order them if needed.
        LOG.warning(_("Invalid date {date} in XML {xml}, preserving XML as text"
            ).format(date=date_error.date.to_struct(), xml=xml))
        date_value.set(modifier=Date.MOD_TEXTONLY, text=xml) 
Example #6
Source File: gui_utilities.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def gtk_listbox_populate_labels(listbox, label_strings):
	"""
	Formats and adds labels to a listbox. Each label is styled and added as a
	separate entry.

	.. versionadded:: 1.13.0

	:param listbox: Gtk Listbox to put the labels in.
	:type listbox: :py:class:`Gtk.listbox`
	:param list label_strings: List of strings to add to the Gtk Listbox as labels.
	"""
	gtk_widget_destroy_children(listbox)
	for label_text in label_strings:
		label = Gtk.Label()
		label.set_markup("<span font=\"smaller\"><tt>{0}</tt></span>".format(saxutils.escape(label_text)))
		label.set_property('halign', Gtk.Align.START)
		label.set_property('use-markup', True)
		label.set_property('valign', Gtk.Align.START)
		label.set_property('visible', True)
		listbox.add(label) 
Example #7
Source File: sanitizer.py    From recruit with Apache License 2.0 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #8
Source File: activecli.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def _display_xml_table_elem(doc, first=False, name=None, out=sys.stdout):
    if first:
        assert name is None
    name = '' if name is None else ' key=%s' % saxutils.quoteattr(name)
    if isinstance(doc, list):
        if not first:
            out.write('<table%s>\n' % name)
        for subdoc in doc:
            _display_xml_table_elem(subdoc, out=out)
        if not first:
            out.write('</table>\n')
    elif isinstance(doc, dict):
        if not first:
            out.write('<table%s>\n' % name)
        for key, subdoc in viewitems(doc):
            _display_xml_table_elem(subdoc, name=key, out=out)
        if not first:
            out.write('</table>\n')
    else:
        out.write('<elem%s>%s</elem>\n' % (name,
                                           saxutils.escape(
                                               str(doc),
                                               entities={'\n': '&#10;'},
                                           ))) 
Example #9
Source File: sanitizer.py    From jbox with MIT License 6 votes vote down vote up
def disallowed_token(self, token, token_type):
        if token_type == tokenTypes["EndTag"]:
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]])
            token["data"] = "<%s%s>" % (token["name"], attrs)
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        if token["type"] in list(tokenTypes.keys()):
            token["type"] = "Characters"
        else:
            token["type"] = tokenTypes["Characters"]

        del token["name"]
        return token 
Example #10
Source File: HTMLTestRunner.py    From flask-restful-example with MIT License 6 votes vote down vote up
def generateReport(self, test, result):
        report_attrs = self.getReportAttributes(result)
        generator = 'HTMLTestRunner %s' % __version__
        stylesheet = self._generate_stylesheet()
        heading = self._generate_heading(report_attrs)
        report = self._generate_report(result)
        ending = self._generate_ending()
        output = self.HTML_TMPL % dict(
            title=saxutils.escape(self.title),
            generator=generator,
            stylesheet=stylesheet,
            heading=heading,
            report=report,
            ending=ending,
        )
        self.stream.write(output.encode('utf8')) 
Example #11
Source File: sanitizer.py    From anpr with Creative Commons Attribution 4.0 International 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #12
Source File: sanitizer.py    From oss-ftp with MIT License 6 votes vote down vote up
def disallowed_token(self, token, token_type):
        if token_type == tokenTypes["EndTag"]:
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]])
            token["data"] = "<%s%s>" % (token["name"], attrs)
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        if token["type"] in list(tokenTypes.keys()):
            token["type"] = "Characters"
        else:
            token["type"] = tokenTypes["Characters"]

        del token["name"]
        return token 
Example #13
Source File: tabulator3.py    From python-in-practice with GNU General Public License v3.0 6 votes vote down vote up
def html_tabulator(rows, items):
    columns, remainder = divmod(len(items), rows)
    if remainder:
        columns += 1
    column = 0
    table = ['<table border="1">\n']
    for item in items:
        if column == 0:
            table.append("<tr>")
        table.append("<td>{}</td>".format(escape(str(item))))
        column += 1
        if column == columns:
            table.append("</tr>\n")
        column %= columns
    if table[-1][-1] != "\n":
        table.append("</tr>\n")
    table.append("</table>\n")
    return "".join(table) 
Example #14
Source File: feedparser.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def parse_declaration(self, i):
        # override internal declaration handler to handle CDATA blocks
        if self.rawdata[i:i+9] == '<![CDATA[':
            k = self.rawdata.find(']]>', i)
            if k == -1:
                # CDATA block began but didn't finish
                k = len(self.rawdata)
                return k
            self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
            return k+3
        else:
            k = self.rawdata.find('>', i)
            if k >= 0:
                return k+1
            else:
                # We have an incomplete CDATA block.
                return k 
Example #15
Source File: sanitizer.py    From lambda-packs with MIT License 6 votes vote down vote up
def disallowed_token(self, token, token_type):
        if token_type == tokenTypes["EndTag"]:
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]])
            token["data"] = "<%s%s>" % (token["name"], attrs)
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        if token["type"] in list(tokenTypes.keys()):
            token["type"] = "Characters"
        else:
            token["type"] = tokenTypes["Characters"]

        del token["name"]
        return token 
Example #16
Source File: subunit2html.py    From os-testr with Apache License 2.0 6 votes vote down vote up
def stopTestRun(self):
        super(HtmlOutput, self).stopTestRun()
        self.stopTime = datetime.datetime.now()
        report_attrs = self._getReportAttributes()
        generator = 'subunit2html %s' % __version__
        heading = self._generate_heading(report_attrs)
        report = self._generate_report()
        ending = self._generate_ending()
        output = TemplateData.HTML_TMPL % dict(
            title=saxutils.escape(TemplateData.DEFAULT_TITLE),
            generator=generator,
            stylesheet=TemplateData.STYLESHEET_TMPL,
            heading=heading,
            report=report,
            ending=ending,
        )
        if self.html_file:
            with open(self.html_file, 'wb') as html_file:
                html_file.write(output.encode('utf8')) 
Example #17
Source File: HTMLTestRunner.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def generateReport(self, test, result):
        report_attrs = self.getReportAttributes(result)
        generator = 'HTMLTestRunner %s' % __version__
        stylesheet = self._generate_stylesheet()
        heading = self._generate_heading(report_attrs)
        report = self._generate_report(result)
        ending = self._generate_ending()
        output = self.HTML_TMPL % dict(
                title=saxutils.escape(self.title),
                generator=generator,
                stylesheet=stylesheet,
                heading=heading,
                report=report,
                ending=ending,
        )
        self.stream.write(output.encode('utf8')) 
Example #18
Source File: sanitizer.py    From FuYiSpider with Apache License 2.0 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #19
Source File: sanitizer.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def disallowed_token(self, token, token_type):
        if token_type == tokenTypes["EndTag"]:
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]])
            token["data"] = "<%s%s>" % (token["name"], attrs)
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        if token["type"] in list(tokenTypes.keys()):
            token["type"] = "Characters"
        else:
            token["type"] = tokenTypes["Characters"]

        del token["name"]
        return token 
Example #20
Source File: sanitizer.py    From Python24 with MIT License 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #21
Source File: tabulator2.py    From python-in-practice with GNU General Public License v3.0 6 votes vote down vote up
def tabulate(rows, items):
        columns, remainder = divmod(len(items), rows)
        if remainder:
            columns += 1
        column = 0
        table = ['<table border="1">\n']
        for item in items:
            if column == 0:
                table.append("<tr>")
            table.append("<td>{}</td>".format(escape(str(item))))
            column += 1
            if column == columns:
                table.append("</tr>\n")
            column %= columns
        if table[-1][-1] != "\n":
            table.append("</tr>\n")
        table.append("</table>\n")
        return "".join(table) 
Example #22
Source File: sanitizer.py    From FuYiSpider with Apache License 2.0 6 votes vote down vote up
def disallowed_token(self, token):
        token_type = token["type"]
        if token_type == "EndTag":
            token["data"] = "</%s>" % token["name"]
        elif token["data"]:
            assert token_type in ("StartTag", "EmptyTag")
            attrs = []
            for (ns, name), v in token["data"].items():
                attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v)))
            token["data"] = "<%s%s>" % (token["name"], ''.join(attrs))
        else:
            token["data"] = "<%s>" % token["name"]
        if token.get("selfClosing"):
            token["data"] = token["data"][:-1] + "/>"

        token["type"] = "Characters"

        del token["name"]
        return token 
Example #23
Source File: tabulator1.py    From python-in-practice with GNU General Public License v3.0 6 votes vote down vote up
def tabulate(self, rows, items):
        columns, remainder = divmod(len(items), rows)
        if remainder:
            columns += 1
        column = 0
        table = ['<table border="1">\n']
        for item in items:
            if column == 0:
                table.append("<tr>")
            table.append("<td>{}</td>".format(escape(str(item))))
            column += 1
            if column == columns:
                table.append("</tr>\n")
            column %= columns
        if table[-1][-1] != "\n":
            table.append("</tr>\n")
        table.append("</table>\n")
        return "".join(table) 
Example #24
Source File: tabulator4.py    From python-in-practice with GNU General Public License v3.0 6 votes vote down vote up
def html_tabulator(rows, items):
    columns, remainder = divmod(len(items), rows)
    if remainder:
        columns += 1
    column = 0
    table = ['<table border="1">\n']
    for item in items:
        if column == 0:
            table.append("<tr>")
        table.append("<td>{}</td>".format(escape(str(item))))
        column += 1
        if column == columns:
            table.append("</tr>\n")
        column %= columns
    if table[-1][-1] != "\n":
        table.append("</tr>\n")
    table.append("</table>\n")
    return "".join(table) 
Example #25
Source File: xep_118.py    From eyeD3 with GNU General Public License v3.0 6 votes vote down vote up
def getXML(self, audio_file):
        tag = audio_file.tag

        pprint = not self.args.no_pretty_print
        nl = "\n" if pprint else ""
        indent = (" " * 2) if pprint else ""

        xml = f"<tune xmlns='http://jabber.org/protocol/tune'>{nl}"
        if tag.artist:
            xml += f"{indent}<artist>{escape(tag.artist)}</artist>{nl}"
        if tag.title:
            xml += f"{indent}<title>{escape(tag.title)}</title>{nl}"
        if tag.album:
            xml += f"{indent}<source>{escape(tag.album)}</source>{nl}"
        xml += f"{indent}<track>file://{escape(str(Path(audio_file.path).absolute()))}</track>{nl}"
        if audio_file.info:
            xml += f"{indent}<length>{audio_file.info.time_secs:.2f}</length>{nl}"
        xml += "</tune>"

        return xml 
Example #26
Source File: e2m3u2bouquet.py    From e2m3u2bouquet with GNU General Public License v3.0 5 votes vote down vote up
def xml_escape(string):
    return escape(string, {'"': '&quot;', "'": "&apos;"}) 
Example #27
Source File: msi.py    From pivy with ISC License 5 votes vote down vote up
def build_wxsfile_header_section(root, spec):
    """ Adds the xml file node which define the package meta-data.
    """
    # Create the needed DOM nodes and add them at the correct position in the tree.
    factory = Document()
    Product = factory.createElement( 'Product' )
    Package = factory.createElement( 'Package' )

    root.childNodes.append( Product )
    Product.childNodes.append( Package )

    # set "mandatory" default values
    if 'X_MSI_LANGUAGE' not in spec:
        spec['X_MSI_LANGUAGE'] = '1033' # select english

    # mandatory sections, will throw a KeyError if the tag is not available
    Product.attributes['Name']         = escape( spec['NAME'] )
    Product.attributes['Version']      = escape( spec['VERSION'] )
    Product.attributes['Manufacturer'] = escape( spec['VENDOR'] )
    Product.attributes['Language']     = escape( spec['X_MSI_LANGUAGE'] )
    Package.attributes['Description']  = escape( spec['SUMMARY'] )

    # now the optional tags, for which we avoid the KeyErrror exception
    if 'DESCRIPTION' in spec:
        Package.attributes['Comments'] = escape( spec['DESCRIPTION'] )

    if 'X_MSI_UPGRADE_CODE' in spec:
        Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] )

    # We hardcode the media tag as our current model cannot handle it.
    Media = factory.createElement('Media')
    Media.attributes['Id']       = '1'
    Media.attributes['Cabinet']  = 'default.cab'
    Media.attributes['EmbedCab'] = 'yes'
    root.getElementsByTagName('Product')[0].childNodes.append(Media)

# this builder is the entry-point for .wxs file compiler. 
Example #28
Source File: exportxml.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def write_line_nofix(self,tagname,value,indent=1):
        """Writes a line, but does not escape characters.
            Use this instead of write_line if the value is already fixed,
            this avoids &amp; becoming &amp;amp;
        """
        if value:
            self.g.write('%s<%s>%s</%s>\n' %
                         ('  '*indent, tagname, value, tagname)) 
Example #29
Source File: HTMLTestRunner.py    From flask-restful-example with MIT License 5 votes vote down vote up
def _generate_heading(self, report_attrs):
        a_lines = []
        for name, value in report_attrs:
            line = self.HEADING_ATTRIBUTE_TMPL % dict(
                name=saxutils.escape(name),
                value=saxutils.escape(value),
            )
            a_lines.append(line)
        heading = self.HEADING_TMPL % dict(
            title=saxutils.escape(self.title),
            parameters=''.join(a_lines),
            description=saxutils.escape(self.description),
        )
        return heading 
Example #30
Source File: subunit2html.py    From os-testr with Apache License 2.0 5 votes vote down vote up
def _generate_heading(self, report_attrs):
        a_lines = []
        for name, value in report_attrs:
            line = TemplateData.HEADING_ATTRIBUTE_TMPL % dict(
                name=saxutils.escape(name),
                value=saxutils.escape(value),
            )
            a_lines.append(line)
        heading = TemplateData.HEADING_TMPL % dict(
            title=saxutils.escape(TemplateData.DEFAULT_TITLE),
            parameters=''.join(a_lines),
            description=saxutils.escape(TemplateData.DEFAULT_DESCRIPTION),
        )
        return heading