当前位置: 首页>>代码示例>>Python>>正文


Python escape.utf8方法代码示例

本文整理汇总了Python中tornado.escape.utf8方法的典型用法代码示例。如果您正苦于以下问题:Python escape.utf8方法的具体用法?Python escape.utf8怎么用?Python escape.utf8使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tornado.escape的用法示例。


在下文中一共展示了escape.utf8方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _render_parts

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
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) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:s3server.py

示例2: redirect

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def redirect(self, url, permanent=False, status=None):
        """重定向到给定的URL(可以选择相对路径).

        如果指定了 ``status`` 参数, 这个值将作为HTTP状态码; 否则
        将通过 ``permanent`` 参数选择301 (永久) 或者 302 (临时).
        默认是 302 (临时重定向).
        """
        if self._headers_written:
            raise Exception("Cannot redirect after headers have been written")
        if status is None:
            status = 301 if permanent else 302
        else:
            assert isinstance(status, int) and 300 <= status <= 399
        self.set_status(status)
        self.set_header("Location", utf8(url))
        self.finish() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:web.py

示例3: render_string

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def render_string(self, template_name, **kwargs):
        """使用给定的参数生成指定模板.

        我们返回生成的字节字符串(以utf8). 为了生成并写一个模板
        作为响应, 使用上面的render().
        """
        # If no template_path is specified, use the path of the calling file
        template_path = self.get_template_path()
        if not template_path:
            frame = sys._getframe(0)
            web_file = frame.f_code.co_filename
            while frame.f_code.co_filename == web_file:
                frame = frame.f_back
            template_path = os.path.dirname(frame.f_code.co_filename)
        with RequestHandler._template_loader_lock:
            if template_path not in RequestHandler._template_loaders:
                loader = self.create_template_loader(template_path)
                RequestHandler._template_loaders[template_path] = loader
            else:
                loader = RequestHandler._template_loaders[template_path]
        t = loader.load(template_name)
        namespace = self.get_template_namespace()
        namespace.update(kwargs)
        return t.generate(**namespace) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:web.py

示例4: decode_signed_value

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def decode_signed_value(secret, name, value, max_age_days=31,
                        clock=None, min_version=None):
    if clock is None:
        clock = time.time
    if min_version is None:
        min_version = DEFAULT_SIGNED_VALUE_MIN_VERSION
    if min_version > 2:
        raise ValueError("Unsupported min_version %d" % min_version)
    if not value:
        return None

    value = utf8(value)
    version = _get_version(value)

    if version < min_version:
        return None
    if version == 1:
        return _decode_signed_value_v1(secret, name, value,
                                       max_age_days, clock)
    elif version == 2:
        return _decode_signed_value_v2(secret, name, value,
                                       max_age_days, clock)
    else:
        return None 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:web.py

示例5: _oauth_signature

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))
    base_string = "&".join(_oauth_escape(e) for e in base_elems)

    key_elems = [escape.utf8(consumer_token["secret"])]
    key_elems.append(escape.utf8(token["secret"] if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1] 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:auth.py

示例6: _oauth10a_signature

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

    See http://oauth.net/core/1.0a/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))

    base_string = "&".join(_oauth_escape(e) for e in base_elems)
    key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))]
    key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1] 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:auth.py

示例7: __init__

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def __init__(self, handler, mask_outgoing=False,
                 compression_options=None):
        WebSocketProtocol.__init__(self, handler)
        self.mask_outgoing = mask_outgoing
        self._final_frame = False
        self._frame_opcode = None
        self._masked_frame = None
        self._frame_mask = None
        self._frame_length = None
        self._fragmented_message_buffer = None
        self._fragmented_message_opcode = None
        self._waiting = None
        self._compression_options = compression_options
        self._decompressor = None
        self._compressor = None
        self._frame_compressed = None
        # The total uncompressed size of all messages received or sent.
        # Unicode messages are encoded to utf8.
        # Only for testing; subject to change.
        self._message_bytes_in = 0
        self._message_bytes_out = 0
        # The total size of all packets received or sent.  Includes
        # the effect of compression, frame overhead, and control frames.
        self._wire_bytes_in = 0
        self._wire_bytes_out = 0 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:27,代码来源:websocket.py

示例8: close

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def close(self, code=None, reason=None):
        """Closes the WebSocket connection."""
        if not self.server_terminated:
            if not self.stream.closed():
                if code is None and reason is not None:
                    code = 1000  # "normal closure" status code
                if code is None:
                    close_data = b''
                else:
                    close_data = struct.pack('>H', code)
                if reason is not None:
                    close_data += utf8(reason)
                self._write_frame(True, 0x8, close_data)
            self.server_terminated = True
        if self.client_terminated:
            if self._waiting is not None:
                self.stream.io_loop.remove_timeout(self._waiting)
                self._waiting = None
            self.stream.close()
        elif self._waiting is None:
            # Give the client a few seconds to complete a clean shutdown,
            # otherwise just close the connection.
            self._waiting = self.stream.io_loop.add_timeout(
                self.stream.io_loop.time() + 5, self._abort) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:websocket.py

示例9: test_body_encoding

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def test_body_encoding(self):
        unicode_body = u("\xe9")
        byte_body = binascii.a2b_hex(b"e9")

        # unicode string in body gets converted to utf8
        response = self.fetch("/echopost", method="POST", body=unicode_body,
                              headers={"Content-Type": "application/blah"})
        self.assertEqual(response.headers["Content-Length"], "2")
        self.assertEqual(response.body, utf8(unicode_body))

        # byte strings pass through directly
        response = self.fetch("/echopost", method="POST",
                              body=byte_body,
                              headers={"Content-Type": "application/blah"})
        self.assertEqual(response.headers["Content-Length"], "1")
        self.assertEqual(response.body, byte_body)

        # Mixing unicode in headers and byte string bodies shouldn't
        # break anything
        response = self.fetch("/echopost", method="POST", body=byte_body,
                              headers={"Content-Type": "application/blah"},
                              user_agent=u("foo"))
        self.assertEqual(response.headers["Content-Length"], "1")
        self.assertEqual(response.body, byte_body) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:httpclient_test.py

示例10: test_cookie_special_char

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def test_cookie_special_char(self):
        response = self.fetch("/special_char")
        headers = sorted(response.headers.get_list("Set-Cookie"))
        self.assertEqual(len(headers), 3)
        self.assertEqual(headers[0], 'equals="a=b"; Path=/')
        self.assertEqual(headers[1], 'quote="a\\"b"; Path=/')
        # python 2.7 octal-escapes the semicolon; older versions leave it alone
        self.assertTrue(headers[2] in ('semicolon="a;b"; Path=/',
                                       'semicolon="a\\073b"; Path=/'),
                        headers[2])

        data = [('foo=a=b', 'a=b'),
                ('foo="a=b"', 'a=b'),
                ('foo="a;b"', 'a;b'),
                # ('foo=a\\073b', 'a;b'),  # even encoded, ";" is a delimiter
                ('foo="a\\073b"', 'a;b'),
                ('foo="a\\"b"', 'a"b'),
                ]
        for header, expected in data:
            logging.debug("trying %r", header)
            response = self.fetch("/get", headers={"Cookie": header})
            self.assertEqual(response.body, utf8(expected)) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:web_test.py

示例11: test_multipart_form

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def test_multipart_form(self):
        # Encodings here are tricky:  Headers are latin1, bodies can be
        # anything (we use utf8 by default).
        response = self.raw_fetch([
            b"POST /multipart HTTP/1.0",
            b"Content-Type: multipart/form-data; boundary=1234567890",
            b"X-Header-encoding-test: \xe9",
        ],
            b"\r\n".join([
                b"Content-Disposition: form-data; name=argument",
                b"",
                u("\u00e1").encode("utf-8"),
                b"--1234567890",
                u('Content-Disposition: form-data; name="files"; filename="\u00f3"').encode("utf8"),
                b"",
                u("\u00fa").encode("utf-8"),
                b"--1234567890--",
                b"",
            ]))
        data = json_decode(response)
        self.assertEqual(u("\u00e9"), data["header"])
        self.assertEqual(u("\u00e1"), data["argument"])
        self.assertEqual(u("\u00f3"), data["filename"])
        self.assertEqual(u("\u00fa"), data["filebody"]) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:httpserver_test.py

示例12: render_xml

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def render_xml(self, value):
        assert isinstance(value, dict) and len(value) == 1
        self.set_header("Content-Type", "application/xml; charset=UTF-8")
        name = value.keys()[0]
        parts = []
        parts.append('<' + escape.utf8(name) +
                     ' xmlns="http://doc.s3.amazonaws.com/2006-03-01">')
        self._render_parts(value.values()[0], parts)
        parts.append('</' + escape.utf8(name) + '>')
        self.finish('<?xml version="1.0" encoding="UTF-8"?>\n' +
                    ''.join(parts)) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:13,代码来源:s3server.py

示例13: write

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def write(self, chunk):
        """把给定块写到输出buffer.

        为了把输出写到网络, 使用下面的flush()方法.

        如果给定的块是一个字典, 我们会把它作为JSON来写同时会把响应头
        设置为 ``application/json``. (如果你写JSON但是设置不同的
        ``Content-Type``,  可以调用set_header *在调用write()之后* ).

        注意列表不能转换为JSON 因为一个潜在的跨域安全漏洞. 所有的JSON
        输出应该包在一个字典中. 更多细节参考
        http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ 和
        https://github.com/facebook/tornado/issues/1009
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish()")
        if not isinstance(chunk, (bytes, unicode_type, dict)):
            message = "write() only accepts bytes, unicode, and dict objects"
            if isinstance(chunk, list):
                message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
            raise TypeError(message)
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:28,代码来源:web.py

示例14: _decode_xsrf_token

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def _decode_xsrf_token(self, cookie):
        """把_get_raw_xsrf_token返回的cookie字符串转换成元组形式.
        """

        try:
            m = _signed_value_version_re.match(utf8(cookie))

            if m:
                version = int(m.group(1))
                if version == 2:
                    _, mask, masked_token, timestamp = cookie.split("|")

                    mask = binascii.a2b_hex(utf8(mask))
                    token = _websocket_mask(
                        mask, binascii.a2b_hex(utf8(masked_token)))
                    timestamp = int(timestamp)
                    return version, token, timestamp
                else:
                    # Treat unknown versions as not present instead of failing.
                    raise Exception("Unknown xsrf cookie version")
            else:
                version = 1
                try:
                    token = binascii.a2b_hex(utf8(cookie))
                except (binascii.Error, TypeError):
                    token = utf8(cookie)
                # We don't have a usable timestamp in older versions.
                timestamp = int(time.time())
                return (version, token, timestamp)
        except Exception:
            # Catch exceptions and return nothing instead of failing.
            gen_log.debug("Uncaught exception in _decode_xsrf_token",
                          exc_info=True)
            return None, None, None 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:36,代码来源:web.py

示例15: check_xsrf_cookie

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import utf8 [as 别名]
def check_xsrf_cookie(self):
        """确认 ``_xsrf`` cookie匹配 ``_xsrf`` 参数.

        为了预防cross-site请求伪造, 我们设置一个 ``_xsrf``
        cookie和包含相同值的一个non-cookie字段在所有
        ``POST`` 请求中. 如果这两个不匹配, 我们拒绝这个
        表单提交作为一个潜在的伪造请求.

        ``_xsrf`` 的值可以被设置为一个名为 ``_xsrf`` 的表单字段或
        在一个名为 ``X-XSRFToken`` 或 ``X-CSRFToken`` 的自定义
        HTTP头部(后者被接受为了兼容Django).

        查看 http://en.wikipedia.org/wiki/Cross-site_request_forgery

        发布1.1.1 之前, 这个检查会被忽略如果当前的HTTP头部是
        ``X-Requested-With: XMLHTTPRequest`` . 这个异常已被证明是
        不安全的并且已经被移除. 更多信息请查看
        http://www.djangoproject.com/weblog/2011/feb/08/security/
        http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails

        .. versionchanged:: 3.2.2
           添加cookie 2版本的支持. 支持版本1和2.
        """
        token = (self.get_argument("_xsrf", None) or
                 self.request.headers.get("X-Xsrftoken") or
                 self.request.headers.get("X-Csrftoken"))
        if not token:
            raise HTTPError(403, "'_xsrf' argument missing from POST")
        _, token, _ = self._decode_xsrf_token(token)
        _, expected_token, _ = self._get_raw_xsrf_token()
        if not _time_independent_equals(utf8(token), utf8(expected_token)):
            raise HTTPError(403, "XSRF cookie does not match POST argument") 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:34,代码来源:web.py


注:本文中的tornado.escape.utf8方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。