我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tornado.escape.xhtml_escape()。
def get_upload_text_data(handler): try: text_data = {} text_data['result'] = 'fail' text_data['con'] = tornado.escape.xhtml_escape(handler.get_argument('con')).replace('&nbsp',' ').replace('<br>','<br>') text_data['title1'] = tornado.escape.xhtml_escape(handler.get_argument('title1')).replace('&nbsp',' ').replace('<br>','<br>') text_data['title2'] = tornado.escape.xhtml_escape(handler.get_argument('title2')).replace('&nbsp',' ').replace('<br>','<br>') text_data['description'] = tornado.escape.xhtml_escape(handler.get_argument('description')).replace('<br>','<br>').replace('&nbsp',' ') text_data['year'] = tornado.escape.xhtml_escape(handler.get_argument('year')) text_data['month'] = tornado.escape.xhtml_escape(handler.get_argument('month')) text_data['background_color'] = tornado.escape.xhtml_escape(handler.get_argument('background_color')) text_data['result'] = 'success' return text_data except Exception as e: print(str(e)) return text_data
def generate(self, **kwargs): """Generate this template with the given arguments.""" namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "linkify": escape.linkify, "datetime": datetime, "_utf8": escape.utf8, # for internal use "_string_types": (unicode, bytes_type), } namespace.update(self.namespace) namespace.update(kwargs) exec self.compiled in namespace execute = namespace["_execute"] try: return execute() except Exception: formatted_code = _format_code(self.code).rstrip() logging.error("%s code:\n%s", self.name, formatted_code) raise
def _render_parts(self, value, parts=[]): if isinstance(value, (unicode, bytes_type)): parts.append(escape.xhtml_escape(value)) elif isinstance(value, int) or isinstance(value, long): parts.append(str(value)) elif isinstance(value, datetime.datetime): parts.append(value.strftime("%Y-%m-%dT%H:%M:%S.000Z")) elif isinstance(value, dict): for name, subvalue in value.iteritems(): if not isinstance(subvalue, list): subvalue = [subvalue] for subsubvalue in subvalue: parts.append('<' + escape.utf8(name) + '>') self._render_parts(subsubvalue, parts) parts.append('</' + escape.utf8(name) + '>') else: raise Exception("Unknown S3 value type %r", value)
def _render_parts(self, value, parts=[]): if isinstance(value, (unicode, bytes)): parts.append(escape.xhtml_escape(value)) elif isinstance(value, int) or isinstance(value, long): parts.append(str(value)) elif isinstance(value, datetime.datetime): parts.append(value.strftime("%Y-%m-%dT%H:%M:%S.000Z")) elif isinstance(value, dict): for name, subvalue in value.iteritems(): if not isinstance(subvalue, list): subvalue = [subvalue] for subsubvalue in subvalue: parts.append('<' + escape.utf8(name) + '>') self._render_parts(subsubvalue, parts) parts.append('</' + escape.utf8(name) + '>') else: raise Exception("Unknown S3 value type %r", value)
def broadcast_image(self, user, image_url, room_id, nsfw_flag=False): """ Broadcast an image message to the given room. Stores the image in the s3 bucket, if available, setting the img tag's src to the cache. If s3 is unavailable, the img src is the original url. Images are wrapping in an a tag with the original url as the href. :param user: user sending the message :param image_url: url of the image :param room_id: room receiving the message """ image_src_url = retrieve_image_in_s3(image_url, self.bucket) new_message = {'user': user, 'color': users[user]['color'], 'image_url': xhtml_escape(image_url), 'image_src_url': xhtml_escape(image_src_url), 'nsfw_flag': nsfw_flag, # 'message': "<a href=\"{}\" target=\"_blank\"><img src=\"{}\" /></a>".format( # xhtml_escape(image_url), xhtml_escape(image_src_url)), 'time': time.time(), 'room': room_id} rooms[room_id]['history'].append(new_message) self.broadcast(self.participants, {'type': 'chatMessage', 'data': new_message})
def get_description(self, raw=False): """ Returns desciption, escapes double quotes if sans_quotes is True, used for rendering description inside fields. """ description = self.description if not description: description = '' if not raw: #description = escape.xhtml_escape(description) extra_params = 'target="_blank" rel="nofollow"' description = escape.linkify(description, True, extra_params=extra_params) #re_hash = re.compile(r'#[0-9a-zA-Z+]*',re.IGNORECASE) #for iterator in re_hash.finditer(description): description = re.sub(r'(\A|\s)#(\w+)', r'\1<a href="/tag/\2">#\2</a>', description) description = description.replace('\n', '<br>') return description
def generate(self, **kwargs): """Generate this template with the given arguments.""" namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "linkify": escape.linkify, "datetime": datetime, "_tt_utf8": escape.utf8, # for internal use "_tt_string_types": (unicode_type, bytes), # __name__ and __loader__ allow the traceback mechanism to find # the generated source code. "__name__": self.name.replace('.', '_'), "__loader__": ObjectDict(get_source=lambda name: self.code), } namespace.update(self.namespace) namespace.update(kwargs) exec_in(self.compiled, namespace) execute = namespace["_tt_execute"] # Clear the traceback module's cache of source data now that # we've generated a new template (mainly for this module's # unittests, where different tests reuse the same name). linecache.clearcache() return execute()
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None, whitespace=None): """Construct a template loader. :arg str autoescape: The name of a function in the template namespace, such as "xhtml_escape", or ``None`` to disable autoescaping by default. :arg dict namespace: A dictionary to be added to the default template namespace, or ``None``. :arg str whitespace: A string specifying default behavior for whitespace in templates; see `filter_whitespace` for options. Default is "single" for files ending in ".html" and ".js" and "all" for other files. .. versionchanged:: 4.3 Added ``whitespace`` parameter. """ self.autoescape = autoescape self.namespace = namespace or {} self.whitespace = whitespace self.templates = {} # self.lock protects self.templates. It's a reentrant lock # because templates may load other templates via `include` or # `extends`. Note that thanks to the GIL this code would be safe # even without the lock, but could lead to wasted work as multiple # threads tried to compile the same template simultaneously. self.lock = threading.RLock()
def generate(self, writer): writer.write_line("_tt_tmp = %s" % self.expression, self.line) writer.write_line("if isinstance(_tt_tmp, _tt_string_types):" " _tt_tmp = _tt_utf8(_tt_tmp)", self.line) writer.write_line("else: _tt_tmp = _tt_utf8(str(_tt_tmp))", self.line) if not self.raw and writer.current_template.autoescape is not None: # In python3 functions like xhtml_escape return unicode, # so we have to convert to utf8 again. writer.write_line("_tt_tmp = _tt_utf8(%s(_tt_tmp))" % writer.current_template.autoescape, self.line) writer.write_line("_tt_append(_tt_tmp)", self.line)
def test_xhtml_escape(self): tests = [ ("<foo>", "<foo>"), (u("<foo>"), u("<foo>")), (b"<foo>", b"<foo>"), ("<>&\"'", "<>&"'"), ("&", "&amp;"), (u("<\u00e9>"), u("<\u00e9>")), (b"<\xc3\xa9>", b"<\xc3\xa9>"), ] for unescaped, escaped in tests: self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped)) self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped)))
def test_escape_return_types(self): # On python2 the escape methods should generally return the same # type as their argument self.assertEqual(type(xhtml_escape("foo")), str) self.assertEqual(type(xhtml_escape(u("foo"))), unicode_type)
def get_query_argument(self, name, default= object(), strip=True): val = super().get_query_argument(name, default, strip) if isinstance(val, str): return xhtml_escape(val) return val
def __xhtml_escape_str(obj): return xhtml_escape(obj)
def post(self): password = xhtml_escape(self.get_argument("password")) if password == options.password: self.set_secure_cookie("user", "FG21SIM") self.redirect(self.reverse_url("index")) else: # Password incorrect self.render("login.html", error="Incorrect password!")
def getArgument(self,name): rawArg = self.handler.get_argument(name) return xhtml_escape(rawArg)
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None): """Creates a template loader. root_directory may be the empty string if this loader does not use the filesystem. autoescape must be either None or a string naming a function in the template namespace, such as "xhtml_escape". """ self.autoescape = autoescape self.namespace = namespace or {} self.templates = {}
def generate(self, writer): writer.write_line("_tmp = %s" % self.expression) writer.write_line("if isinstance(_tmp, _string_types):" " _tmp = _utf8(_tmp)") writer.write_line("else: _tmp = _utf8(str(_tmp))") if not self.raw and writer.current_template.autoescape is not None: # In python3 functions like xhtml_escape return unicode, # so we have to convert to utf8 again. writer.write_line("_tmp = _utf8(%s(_tmp))" % writer.current_template.autoescape) writer.write_line("_append(_tmp)")
def test_xhtml_escape(self): tests = [ ("<foo>", "<foo>"), (u"<foo>", u"<foo>"), (b("<foo>"), b("<foo>")), ("<>&\"", "<>&""), ("&", "&amp;"), ] for unescaped, escaped in tests: self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped)) self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped)))
def test_escape_return_types(self): # On python2 the escape methods should generally return the same # type as their argument self.assertEqual(type(xhtml_escape("foo")), str) self.assertEqual(type(xhtml_escape(u"foo")), unicode)
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None): """``autoescape`` must be either None or a string naming a function in the template namespace, such as "xhtml_escape". """ self.autoescape = autoescape self.namespace = namespace or {} self.templates = {} # self.lock protects self.templates. It's a reentrant lock # because templates may load other templates via `include` or # `extends`. Note that thanks to the GIL this code would be safe # even without the lock, but could lead to wasted work as multiple # threads tried to compile the same template simultaneously. self.lock = threading.RLock()
def generate(self, **kwargs): """Generate this template with the given arguments.""" namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "linkify": escape.linkify, "datetime": datetime, "_tt_utf8": escape.utf8, # for internal use "_tt_string_types": (unicode_type, bytes_type), # __name__ and __loader__ allow the traceback mechanism to find # the generated source code. "__name__": self.name.replace('.', '_'), "__loader__": ObjectDict(get_source=lambda name: self.code), } namespace.update(self.namespace) namespace.update(kwargs) exec_in(self.compiled, namespace) execute = namespace["_tt_execute"] # Clear the traceback module's cache of source data now that # we've generated a new template (mainly for this module's # unittests, where different tests reuse the same name). linecache.clearcache() return execute()
def xsrf_form_html(self): """An HTML ``<input/>`` element to be included with all POST forms. It defines the ``_xsrf`` input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the ``xsrf_cookies`` application setting, you must include this HTML within all of your HTML forms. In a template, this method should be called with ``{% module xsrf_form_html() %}`` See `check_xsrf_cookie()` above for more information. """ return '<input type="hidden" name="_xsrf" value="' + \ escape.xhtml_escape(self.xsrf_token) + '"/>'