我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cgi.escape()。
def html(self): value = cgi.escape(self.value, True) if self.readonly: return value self.klass.extend(['text-line', 'controls']) self.attr['type'] = self._type self.attr['placeholder'] = self.placeholder self.attr['value'] = value attr = self._get_attr() data = self._get_data() result = '<input style="100%%" %s %s />' % (attr, data) if self._icon: return '<div class="input-prepend"><span class="add-on"><i class="fa fa-%s"></i></span> %s </div>' % (self._icon, result) else: return result
def handle_qr(abe,page): address = wsgiref.util.shift_path_info(page['env']) if address in (None, '') or page['env']['PATH_INFO'] != '': raise PageNotFound() body = page['body'] page['title'] = 'Address ' + escape(address) version, binaddr = decode_check_address(address) if binaddr is None: body += ['<p>Not a valid address.</p>'] return ret = """<html><body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> <script type="text/javascript" src="http://ecdsa.org/jquery.qrcode.min.js"></script> <div id="qrcode"></div> <script>jQuery('#qrcode').qrcode("bitcoin:%s");</script> </body></html>"""%address abe.do_raw(page, ret) page['content_type']='text/html'
def show_search_results(abe, page, found): if not found: page['body'] = [ '<p>No results found.</p>\n', abe.search_form(page)] return if len(found) == 1: # Undo shift_path_info. sn = posixpath.dirname(page['env']['SCRIPT_NAME']) if sn == '/': sn = '' page['env']['SCRIPT_NAME'] = sn page['env']['PATH_INFO'] = '/' + page['dotdot'] + found[0]['uri'] del(page['env']['QUERY_STRING']) raise Redirect() body = page['body'] body += ['<h3>Search Results</h3>\n<ul>\n'] for result in found: body += [ '<li><a href="', page['dotdot'], escape(result['uri']), '">', escape(result['name']), '</a></li>\n'] body += ['</ul>\n']
def handle_b(abe, page): if page.get('chain') is not None: chain = page['chain'] height = wsgiref.util.shift_path_info(page['env']) try: height = int(height) except Exception: raise PageNotFound() if height < 0 or page['env']['PATH_INFO'] != '': raise PageNotFound() cmd = wsgiref.util.shift_path_info(page['env']) if cmd is not None: raise PageNotFound() # XXX want to support /a/... page['title'] = [escape(chain.name), ' ', height] abe._show_block(page, page['dotdot'] + 'block/', chain, block_number=height) return abe.show_search_results( page, abe.search_hash_prefix( shortlink_block(wsgiref.util.shift_path_info(page['env'])), ('block',)))
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 get_description_message(useHTML, type, doc=None, url=None): """Get the message to display for Describe commands. If useHTML is True, the message will be formatted with HTML tags. """ message = type if useHTML: message = "<strong>{type}</strong>".format(type=message) if doc is not None: if useHTML: message += " — " + cgi.escape(doc) else: message += "\n\n" + format_doc(doc) if url is not None: message += " " if useHTML: message += '<a href="{url}">[docs]</a>'.format(url=url) else: message += "\n\n" + url return message
def addHTMLListings(document, dir): """ Insert HTML source listings into the given document from files in the given directory based on C{html-listing} nodes. Any node in C{document} with a C{class} attribute set to C{html-listing} will have source lines taken from the file named in that node's C{href} attribute (searched for in C{dir}) inserted in place of that node. @type document: A DOM Node or Document @param document: The document within which to make listing replacements. @type dir: C{str} @param dir: The directory in which to find source files containing the referenced HTML listings. @return: C{None} """ for node in domhelpers.findElementsWithAttribute(document, "class", "html-listing"): filename = node.getAttribute("href") val = ('<pre class="htmlsource">\n%s</pre>' % cgi.escape(open(os.path.join(dir, filename)).read())) _replaceWithListing(node, val, filename, "html-listing")
def addPlainListings(document, dir): """ Insert text listings into the given document from files in the given directory based on C{listing} nodes. Any node in C{document} with a C{class} attribute set to C{listing} will have source lines taken from the file named in that node's C{href} attribute (searched for in C{dir}) inserted in place of that node. @type document: A DOM Node or Document @param document: The document within which to make listing replacements. @type dir: C{str} @param dir: The directory in which to find source files containing the referenced text listings. @return: C{None} """ for node in domhelpers.findElementsWithAttribute(document, "class", "listing"): filename = node.getAttribute("href") val = ('<pre>\n%s</pre>' % cgi.escape(open(os.path.join(dir, filename)).read())) _replaceWithListing(node, val, filename, "listing")
def sidebarRenderOwnSettings(self, body, site): title = cgi.escape(site.content_manager.contents["content.json"]["title"], True) description = cgi.escape(site.content_manager.contents["content.json"]["description"], True) privatekey = cgi.escape(self.user.getSiteData(site.address, create=False).get("privatekey", "")) body.append(u""" <li> <label for='settings-title'>Site title</label> <input type='text' class='text' value="{title}" id='settings-title'/> </li> <li> <label for='settings-description'>Site description</label> <input type='text' class='text' value="{description}" id='settings-description'/> </li> <li style='display: none'> <label>Private key</label> <input type='text' class='text long' value="{privatekey}" placeholder='[Ask on signing]'/> </li> <li> <a href='#Save' class='button' id='button-settings'>Save site settings</a> </li> """.format(**locals()))
def sidebarRenderContents(self, body, site): body.append(""" <li> <label>Content publishing</label> <select id='select-contents'> """) for inner_path in sorted(site.content_manager.contents.keys()): body.append(u"<option>%s</option>" % cgi.escape(inner_path, True)) body.append(""" </select> <span class='select-down'>›</span> <a href='#Sign' class='button' id='button-sign'>Sign</a> <a href='#Publish' class='button' id='button-publish'>Publish</a> </li> """)
def process_usage(apis, usage): """Populates usage element of an API dictionary with the usages of that API. Args: apis: Dictionary mapping Chrome Apps API name to polyfill manifest dictionaries. This will be modified. usage: Usage dictionary mapping API names to (filepath, linenum, context, context_linenum) tuples. """ for api_name, api_info in apis.iteritems(): api_info['usage'] = [] for uses in usage[api_name].values(): for filepath, line_num, context, start in uses: context = cgi.escape(context) context = highlight_relevant_line(context, line_num - start, apis) api_info['usage'].append((filepath, line_num, context, start)) # Sort first by file, then by line number. api_info['usage'].sort()
def local_html_escape(data, quote=False): """ Works with bytes. Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ if PY2: import cgi data = cgi.escape(data, quote) return data.replace("'", "'") if quote else data else: import html if isinstance(data, str): return html.escape(data, quote=quote) data = data.replace(b"&", b"&") # Must be done first! data = data.replace(b"<", b"<") data = data.replace(b">", b">") if quote: data = data.replace(b'"', b""") data = data.replace(b'\'', b"'") return data
def set_transport_uri(self, data): print("CurrentURI:\n" + data['CurrentURI']) print("CurrentURIMetaData:\n" + data['CurrentURIMetaData']) send_data = '<InstanceID>0</InstanceID>' add_uri = data['CurrentURI'] if 'raumfeldname' in data: if data['raumfeldname'] == 'Station': if 'TrackURI' in data: add_uri = data['TrackURI'] send_data += "<CurrentURI><![CDATA[" + add_uri + "]]></CurrentURI>" send_data += "<CurrentURIMetaData>" + cgi.escape(data['CurrentURIMetaData']) + "</CurrentURIMetaData>" # + cgi.escape(data['CurrentURIMetaData']) + print(send_data) xml_root = self.host_send_transport("SetAVTransportURI", send_data) return XmlHelper.xml_extract_dict(xml_root, ['SetAVTransportURI'])
def handle_exception(self, exception, debug_mode): """Called if this handler throws an exception during execution. The default behavior is to call self.error(500) and print a stack trace if debug_mode is True. Args: exception: the exception that was thrown debug_mode: True if the web application is running in debug mode """ self.error(500) logging.exception(exception) if debug_mode: lines = ''.join(traceback.format_exception(*sys.exc_info())) self.response.clear() self.response.out.write('<pre>%s</pre>' % (cgi.escape(lines, quote=True)))
def write_error(sock, status_int, reason, mesg): html = textwrap.dedent("""\ <html> <head> <title>%(reason)s</title> </head> <body> <h1><p>%(reason)s</p></h1> %(mesg)s </body> </html> """) % {"reason": reason, "mesg": cgi.escape(mesg)} http = textwrap.dedent("""\ HTTP/1.1 %s %s\r Connection: close\r Content-Type: text/html\r Content-Length: %d\r \r %s""") % (str(status_int), reason, len(html), html) write_nonblock(sock, http.encode('latin1'))
def html_params(**kwargs): """ Generate HTML parameters from inputted keyword arguments. The output value is sorted by the passed keys, to provide consistent output each time this function is called with the same parameters. Because of the frequent use of the normally reserved keywords `class` and `for`, suffixing these with an underscore will allow them to be used. >>> html_params(name='text1', id='f', class_='text') == 'class="text" id="f" name="text1"' True """ params = [] for k,v in sorted(iteritems(kwargs)): if k in ('class_', 'class__', 'for_'): k = k[:-1] if v is True: params.append(k) else: params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True))) return ' '.join(params)
def get_constituency_info(db,constituency_id): cursor = db.cursor() cursor.execute('''Select c.id, c.name, c.constituency_code, c.state_id, s.name, c.result_status from constituency c inner join state s on s.id = c.state_id where c.id = ''' + constituency_id + ''';''') row = cursor.fetchone() voting_status=cgi.escape(row[5]) voting_status=voting_status.title() if (voting_status!="NOT_STARTED") else "Not Started" constituency = {"id": row[0], "name": row[1], \ "constituency_code": cgi.escape(row[2]), \ "state_id": row[3], "state_name": cgi.escape(row[4]),\ "voting_status":voting_status} result = get_constituency_result_1(db,constituency_id) for result_item in result.iterkeys(): constituency[result_item]=result[result_item] return json.dumps(constituency)
def get_constituency_result_1(db,constituency_id): cursor = db.cursor() cursor.execute('''SELECT ca.id, ca.fullname, p.id, p.name, r.time_start, r.votes, p.symbol FROM results r, candidate_constituency c_c, candidate ca, constituency co, party p where c_c.constituency_id=co.id and c_c.candidate_id=ca.id and c_c.party_id=p.id and r.candidate_id=ca.id and r.constituency_id=co.id and r.active=1 and c_c.election="2014" and r.constituency_id='''+ constituency_id +''' order by r.votes desc;''') output={'total_votes':0} results=[] for row in cursor.fetchall(): temp_map={} temp_map['candidate_id']=row[0] temp_map['candidate_name']=cgi.escape(row[1]).title() temp_map['party_id']=row[2] temp_map['party_name']=cgi.escape(row[3]).title() temp_map['votes']=row[5] temp_map['party_symbol']=row[6] output['total_votes']=output['total_votes']+row[5] results.append(temp_map) output['result_list']=results return output
def get_constituency_result_2009(db,constituency_id): cursor = db.cursor() cursor.execute('''SELECT ca.id, ca.fullname, p.id, p.name, l.votes FROM last_time_results l, candidate ca, constituency co, party p where l.constituency_id=co.id and l.candidate_id=ca.id and l.party_id=p.id and l.candidate_id=ca.id and l.constituency_id=co.id and l.constituency_id='''+ constituency_id +''' order by l.votes desc;''') results=[] total_votes=0 for row in cursor.fetchall(): temp_map={} temp_map['candidate_id']=row[0] temp_map['candidate_name']=cgi.escape(row[1]).title() temp_map['party_id']=row[2] temp_map['party_name']=cgi.escape(row[3]).title() temp_map['votes']=row[4] total_votes=total_votes+row[4] results.append(temp_map) new_results = [] for rec in results: rec['total_votes']=total_votes new_results.append(rec) return json.dumps(new_results)
def get_candidate_list(db,param): cursor = db.cursor() cursor.execute('''SELECT ca.id, ca.fullname, co.id, co.name, p.id, p.name from candidate ca, candidate_constituency c_c, constituency co, party p where ca.id=c_c.candidate_id and c_c.constituency_id=co.id and c_c.party_id=p.id ''') output=[] for row in cursor.fetchall(): temp={} temp['candidate_id']=row[0] temp['candidate_name']=cgi.escape(row[1]) temp['constituency_id']=row[2] temp['constituency_name']=cgi.escape(row[3]) temp['party_id']=row[4] temp['party_name']=cgi.escape(row[5]) output.append(temp) return json.dumps(output);
def document(self): """Render the error document""" original_request = request.environ.get('pylons.original_request') original_response = request.environ.get('pylons.original_response') # When a request (e.g. from a web-bot) is direct, not a redirect # from a page. #1176 if not original_response: return 'There is no error.' # Bypass error template for API operations. if (original_request and (original_request.path.startswith('/api') or original_request.path.startswith('/fanstatic'))): return original_response.body # If the charset has been lost on the middleware stack, use the # default one (utf-8) if not original_response.charset and original_response.default_charset: original_response.charset = original_response.default_charset # Otherwise, decorate original response with error template. c.content = literal(original_response.unicode_body) or \ cgi.escape(request.GET.get('message', '')) c.prefix = request.environ.get('SCRIPT_NAME', ''), c.code = cgi.escape(request.GET.get('code', str(original_response.status_int))), return render('error_document_template.html')
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 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