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'
python类escape()的实例源码
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
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))
def endElement(self, name, value, connection):
self._xml.write("%s</%s>" % (cgi.escape(value).replace("&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
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)
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'
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
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("'", "'")
return data
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
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])
def _get_data(self):
return ' '.join(['data-%s="%s"' % (name, cgi.escape(value, True)) for (name, value) in self.data.items() if value])
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))
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))
def draggable(self, data={}):
self.klass.append('kss-draggable')
self.data['drag'] = cgi.escape(json.dumps(data), True)
return self
def __init__(self, title='', **attr):
title = cgi.escape(title)
text.__init__(self, title, **attr)
def _escape(self, data):
return ', '.join(['%s="%s"' % (key, cgi.escape(value, True)) for key, value in data.items()])
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
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
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
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