python类escape()的实例源码

fcgi.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
sanitizer.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def strip(self, rawstring, escape=True):
        """
        Returns the argument stripped of potentially harmful
        HTML or Javascript code

        @type escape: boolean
        @param escape: If True (default) it escapes the potentially harmful
          content, otherwise remove it
        """

        if not isinstance(rawstring, str):
            return str(rawstring)
        for tag in self.requires_no_close:
            rawstring = rawstring.replace("<%s/>" % tag, "<%s />" % tag)
        if not escape:
            self.strip_disallowed = True
        self.result = ''
        self.feed(rawstring)
        for endtag in self.open_tags:
            if endtag not in self.requires_no_close:
                self.result += '</%s>' % endtag
        return self.result
shell.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def callback():
    app = request.args[0]
    command = request.vars.statement
    escape = command[:1] != '!'
    history = session['history:' + app] = session.get(
        'history:' + app, gluon.contrib.shell.History())
    if not escape:
        command = command[1:]
    if command == '%reset':
        reset()
        return '*** reset ***'
    elif command[0] == '%':
        try:
            command = session['commands:' + app][int(command[1:])]
        except ValueError:
            return ''
    session['commands:' + app].append(command)
    environ = env(app, True, extra_request=dict(is_https=request.is_https))
    output = gluon.contrib.shell.run(history, command, environ)
    k = len(session['commands:' + app]) - 1
    #output = PRE(output)
    #return TABLE(TR('In[%i]:'%k,PRE(command)),TR('Out[%i]:'%k,output))
    return cgi.escape('In [%i] : %s%s\n' % (k + 1, command, output))
item.py 文件源码 项目:cuny-bdif 作者: aristotle-tek 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def endElement(self, name, value, connection):
        self._xml.write("%s</%s>" % (cgi.escape(value).replace("&amp;amp;", "&amp;"), name))
        if len(self._nodepath) == 0:
            return
        obj = None
        curval = self.get(name)
        if len(self._nodepath) == 1:
            if value or not curval:
                self.set(name, value)
            if self._curobj:
                self._curobj = None
        #elif len(self._nodepath) == 2:
            #self._curobj = None
        elif self._curobj:
            self._curobj.endElement(name, value, connection)
        self._nodepath.pop()
        return None
debug.py 文件源码 项目:ara 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def app_dump():
    lines = ['<table>']

    for attr in sorted(dir(app)):
        attrval = getattr(app, attr)
        lines.append('<tr>')
        lines.append('<td><a href="{url}">{attr}</a></td>'.format(
            url=url_for('debug.app_dump_attr', attr=attr),
            attr=attr))
        lines.append('<td>{_type}</td>'.format(
            _type=cgi.escape(str(type(attrval)))))
        lines.append('<td>{callable}</td>'.format(
            callable=callable(attrval)))
        lines.append('</tr>')

    lines.append('</table>')
    return '\n'.join(lines)
fcgi.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
sanitizer.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def strip(self, rawstring, escape=True):
        """
        Returns the argument stripped of potentially harmful
        HTML or Javascript code

        @type escape: boolean
        @param escape: If True (default) it escapes the potentially harmful
          content, otherwise remove it
        """

        if not isinstance(rawstring, str):
            return str(rawstring)
        for tag in self.requires_no_close:
            rawstring = rawstring.replace("<%s/>" % tag, "<%s />" % tag)
        if not escape:
            self.strip_disallowed = True
        self.result = ''
        self.feed(rawstring)
        for endtag in self.open_tags:
            if endtag not in self.requires_no_close:
                self.result += '</%s>' % endtag
        return self.result
html.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def xmlescape(data, quote=True):
    """
    returns an escaped string of the provided data

    :param data: the data to be escaped
    :param quote: optional (default False)
    """

    # first try the xml function
    if hasattr(data, 'xml') and callable(data.xml):
        return data.xml()

    # otherwise, make it a string
    if not isinstance(data, (str, unicode)):
        data = str(data)
    elif isinstance(data, unicode):
        data = data.encode('utf8', 'xmlcharrefreplace')

    # ... and do the escaping
    data = cgi.escape(data, quote).replace("'", "&#x27;")
    return data
listener.py 文件源码 项目:agent-python-pytest 作者: reportportal 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def pytest_runtest_makereport(self):
        report = (yield).get_result()

        if report.longrepr:
            PyTestService.post_log(
                # Used for support python 2.7
                cgi.escape(report.longreprtext),
                loglevel='ERROR',
            )

        if report.when == 'setup':
            if report.failed:
                # This happens for example when a fixture fails to run
                # causing the test to error
                self.result = 'FAILED'

        if report.when == 'call':
            if report.passed:
                item_result = 'PASSED'
            elif report.skipped:
                item_result = 'SKIPPED'
            else:
                item_result = 'FAILED'
            self.result = item_result
ui_form.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _get_attr(self):
        attr = self.attr.items()
        if self.id:
            attr.append(('id', self.id))
        attr.append(('name', self.name))
        attr.append(('class', ' '.join(self.klass)))
        attr.append(('onchange', _gen_on_js(self, 'change')))
        attr.append(('onblur', _gen_on_js(self, 'blur')))
        return ' '.join(['%s="%s"' % (name, cgi.escape(str(value), True)) for (name, value) in attr if value])
ui_form.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _get_data(self):
        return ' '.join(['data-%s="%s"' % (name, cgi.escape(value, True)) for (name, value) in self.data.items() if value])
ui_form.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def html(self):
        if not isinstance(self.value, (str, unicode)):
            self.value = json.dumps(self.value)
        return '<input type="hidden" name="%s" value="%s" />' % (self.name, cgi.escape(self.value, True))
ui_form.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def html(self):
        value = cgi.escape(self.value, True)
        if self.readonly: return value

        self.klass.extend(['controls', self.__class__.__name__])

        attr = self._get_attr()
        data = self._get_data()
        return '<select %s %s>%s</select>' % (attr, data, _gen_select_options(self.options, self.value))
components.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def draggable(self, data={}):
        self.klass.append('kss-draggable')
        self.data['drag'] = cgi.escape(json.dumps(data), True)
        return self
components.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, title='', **attr):
        title = cgi.escape(title)
        text.__init__(self, title, **attr)
components.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _escape(self, data):
        return ', '.join(['%s="%s"' % (key, cgi.escape(value, True)) for key, value in data.items()])
components.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def subgraph(self, name, nodes, title='', url='', style='dotted', color='black'):
        self.dots.append('subgraph cluster_%s{ label="%s"; URL="%s";style="%s";color="%s";%s }'\
            % (name, cgi.escape(title, True), url, style, color, '\n'.join(nodes)))
        return self
SimpleHTTPServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def list_directory(self, path):
        """Helper to produce a directory listing (absent index.html).

        Return value is either a file object, or None (indicating an
        error).  In either case, the headers are sent, making the
        interface the same as for send_head().

        """
        try:
            list = os.listdir(path)
        except os.error:
            self.send_error(404, "No permission to list directory")
            return None
        list.sort(key=lambda a: a.lower())
        f = StringIO()
        displaypath = cgi.escape(urllib.unquote(self.path))
        f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
        f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
        f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
        f.write("<hr>\n<ul>\n")
        for name in list:
            fullname = os.path.join(path, name)
            displayname = linkname = name
            # Append / for directories or @ for symbolic links
            if os.path.isdir(fullname):
                displayname = name + "/"
                linkname = name + "/"
            if os.path.islink(fullname):
                displayname = name + "@"
                # Note: a link to a directory displays with @ and links with /
            f.write('<li><a href="%s">%s</a>\n'
                    % (urllib.quote(linkname), cgi.escape(displayname)))
        f.write("</ul>\n<hr>\n</body>\n</html>\n")
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        encoding = sys.getfilesystemencoding()
        self.send_header("Content-type", "text/html; charset=%s" % encoding)
        self.send_header("Content-Length", str(length))
        self.end_headers()
        return f
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def styles_to_html(formatter, styles, condensed):
    # type: (CodeFormatter, Iterable[Style], bool) -> str
    equivalents = condense_option_values(formatter, styles, condensed)
    styletexts = [formatter.styletext(s) for s in equivalents if s]
    fragments = [cgi.escape(unistr(e)) for e in styletexts]
    or_join = unistr("------------ or ------------\n").join
    html = '<pre>' + or_join(fragments).replace('\n', '<br/>') + '</pre>'
    return html
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def lines_from_sourcepairs(pairs, numlines=2, enc='utf-8'):
        # type: (List[BytesPair], int, str) -> Tuple[List[str], List[str]]
        def safeunistr(s):
            # type: (bytes) -> str
            # The bytes 0 and 1 that appear in the intermediate result of
            # difflib.HtmlDiff.make_table are replaced by opening and closing span tags.
            # If the input to make_table already contains 0 and 1 bytes we get mismatched
            # span tags.
            # We use '\x02' as escape character and encode '\x00', '\x01', '\x02' as
            # '\x02' followed by the digit 0, 1, 2 respectively.
            def escape_zeroonetwo(m):
                return b'\x02' + int2byte(ord('0') + ord(m.group(0)))

            s = re.sub(b'[\x00-\x02]', escape_zeroonetwo, s)
            return surrdecode(s, enc=enc)

        a = [a for a, _ in pairs]
        b = [b for _, b in pairs]
        a = concat_sources(a, numlines=numlines).splitlines(True)
        b = concat_sources(b, numlines=numlines).splitlines(True)
        atext = list(map(safeunistr, a))
        btext = list(map(safeunistr, b))
        return atext, btext


# yapf: disable
# ----------------------------------------------------------------------
# http://stackoverflow.com/questions/1707890/
#           fast-way-to-filter-illegal-xml-unicode-chars-in-python


问题


面经


文章

微信
公众号

扫码关注公众号