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


Python escape.native_str方法代码示例

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


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

示例1: set_status

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def set_status(self, status_code, reason=None):
        """设置响应的状态码.

        :arg int status_code: 响应状态码. 如果 ``reason`` 是 ``None``,
            它必须存在于 `httplib.responses <http.client.responses>`.
        :arg string reason: 用人类可读的原因短语来描述状态码.
            如果是 ``None``, 它会由来自
            `httplib.responses <http.client.responses>` 的reason填满.
        """
        self._status_code = status_code
        if reason is not None:
            self._reason = escape.native_str(reason)
        else:
            try:
                self._reason = httputil.responses[status_code]
            except KeyError:
                raise ValueError("unknown status code %d", status_code) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:web.py

示例2: parse_response_start_line

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def parse_response_start_line(line):
    """Returns a (version, code, reason) tuple for an HTTP 1.x response line.

    The response is a `collections.namedtuple`.

    >>> parse_response_start_line("HTTP/1.1 200 OK")
    ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
    """
    line = native_str(line)
    match = re.match("(HTTP/1.[0-9]) ([0-9]+) ([^\r]*)", line)
    if not match:
        raise HTTPInputError("Error parsing response start line")
    return ResponseStartLine(match.group(1), int(match.group(2)),
                             match.group(3))

# _parseparam and _parse_header are copied and modified from python2.7's cgi.py
# The original 2.7 version of this code did not correctly support some
# combinations of semicolons and double quotes.
# It has also been modified to support valueless parameters as seen in
# websocket extension negotiations. 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:22,代码来源:httputil.py

示例3: main

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def main():
    from tornado.options import define, options, parse_command_line
    define("print_headers", type=bool, default=False)
    define("print_body", type=bool, default=True)
    define("follow_redirects", type=bool, default=True)
    define("validate_cert", type=bool, default=True)
    args = parse_command_line()
    client = HTTPClient()
    for arg in args:
        try:
            response = client.fetch(arg,
                                    follow_redirects=options.follow_redirects,
                                    validate_cert=options.validate_cert,
                                    )
        except HTTPError as e:
            if e.response is not None:
                response = e.response
            else:
                raise
        if options.print_headers:
            print(response.headers)
        if options.print_body:
            print(native_str(response.body))
    client.close() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:httpclient.py

示例4: _on_access_token

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def _on_access_token(self, redirect_uri, client_id, client_secret,
                         future, fields, response):
        if response.error:
            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
            return

        args = urlparse.parse_qs(escape.native_str(response.body))
        session = {
            "access_token": args["access_token"][-1],
            "expires": args.get("expires")
        }

        self.facebook_request(
            path="/me",
            callback=functools.partial(
                self._on_get_user_info, future, session, fields),
            access_token=session["access_token"],
            fields=",".join(fields)
        ) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:21,代码来源:auth.py

示例5: _curl_header_callback

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def _curl_header_callback(self, headers, header_callback, header_line):
        header_line = native_str(header_line)
        if header_callback is not None:
            self.io_loop.add_callback(header_callback, header_line)
        # header_line as returned by curl includes the end-of-line characters.
        # whitespace at the start should be preserved to allow multi-line headers
        header_line = header_line.rstrip()
        if header_line.startswith("HTTP/"):
            headers.clear()
            try:
                (__, __, reason) = httputil.parse_response_start_line(header_line)
                header_line = "X-Http-Reason: %s" % reason
            except httputil.HTTPInputError:
                return
        if not header_line:
            return
        headers.parse_line(header_line) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:curl_httpclient.py

示例6: parse_config_file

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def parse_config_file(self, path, final=True):
        """Parses and loads the Python config file at the given path.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.

        .. versionchanged:: 4.1
           Config files are now always interpreted as utf-8 instead of
           the system default encoding.
        """
        config = {}
        with open(path, 'rb') as f:
            exec_in(native_str(f.read()), config, config)
        for name in config:
            normalized = self._normalize_name(name)
            if normalized in self._options:
                self._options[normalized].set(config[name])

        if final:
            self.run_parse_callbacks() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:23,代码来源:options.py

示例7: test_custom_escape

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def test_custom_escape(self):
        loader = DictLoader({"foo.py":
                             "{% autoescape py_escape %}s = {{ name }}\n"})

        def py_escape(s):
            self.assertEqual(type(s), bytes)
            return repr(native_str(s))

        def render(template, name):
            return loader.load(template).generate(py_escape=py_escape,
                                                  name=name)
        self.assertEqual(render("foo.py", "<html>"),
                         b"s = '<html>'\n")
        self.assertEqual(render("foo.py", "';sys.exit()"),
                         b"""s = "';sys.exit()"\n""")
        self.assertEqual(render("foo.py", ["not a string"]),
                         b"""s = "['not a string']"\n""") 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:template_test.py

示例8: _parse_headers

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def _parse_headers(self, data):
        # The lstrip removes newlines that some implementations sometimes
        # insert between messages of a reused connection.  Per RFC 7230,
        # we SHOULD ignore at least one empty line before the request.
        # http://tools.ietf.org/html/rfc7230#section-3.5
        data = native_str(data.decode('latin1')).lstrip("\r\n")
        # RFC 7230 section allows for both CRLF and bare LF.
        eol = data.find("\n")
        start_line = data[:eol].rstrip("\r")
        try:
            headers = httputil.HTTPHeaders.parse(data[eol:])
        except ValueError:
            # probably form split() if there was no ':' in the line
            raise httputil.HTTPInputError("Malformed HTTP headers: %r" %
                                          data[eol:100])
        return start_line, headers 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:http1connection.py

示例9: set_status

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def set_status(self, status_code: int, reason: str = None) -> None:
        """Sets the status code for our response.

        :arg int status_code: Response status code.
        :arg str reason: Human-readable reason phrase describing the status
            code. If ``None``, it will be filled in from
            `http.client.responses` or "Unknown".

        .. versionchanged:: 5.0

           No longer validates that the response code is in
           `http.client.responses`.
        """
        self._status_code = status_code
        if reason is not None:
            self._reason = escape.native_str(reason)
        else:
            self._reason = httputil.responses.get(status_code, "Unknown") 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:20,代码来源:web.py

示例10: _curl_header_callback

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def _curl_header_callback(
        self,
        headers: httputil.HTTPHeaders,
        header_callback: Callable[[str], None],
        header_line_bytes: bytes,
    ) -> None:
        header_line = native_str(header_line_bytes.decode("latin1"))
        if header_callback is not None:
            self.io_loop.add_callback(header_callback, header_line)
        # header_line as returned by curl includes the end-of-line characters.
        # whitespace at the start should be preserved to allow multi-line headers
        header_line = header_line.rstrip()
        if header_line.startswith("HTTP/"):
            headers.clear()
            try:
                (__, __, reason) = httputil.parse_response_start_line(header_line)
                header_line = "X-Http-Reason: %s" % reason
            except httputil.HTTPInputError:
                return
        if not header_line:
            return
        headers.parse_line(header_line) 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:24,代码来源:curl_httpclient.py

示例11: set_status

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def set_status(self, status_code, reason=None):
        """Sets the status code for our response.

        :arg int status_code: Response status code. If ``reason`` is ``None``,
            it must be present in `httplib.responses <http.client.responses>`.
        :arg string reason: Human-readable reason phrase describing the status
            code. If ``None``, it will be filled in from
            `httplib.responses <http.client.responses>`.
        """
        self._status_code = status_code
        if reason is not None:
            self._reason = escape.native_str(reason)
        else:
            try:
                self._reason = httputil.responses[status_code]
            except KeyError:
                raise ValueError("unknown status code %d", status_code) 
开发者ID:viewfinderco,项目名称:viewfinder,代码行数:19,代码来源:web.py

示例12: _on_access_token

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def _on_access_token(self, redirect_uri, client_id, client_secret,
                         future, fields, response):
        if response.error:
            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
            return

        args = escape.parse_qs_bytes(escape.native_str(response.body))
        session = {
            "access_token": args["access_token"][-1],
            "expires": args.get("expires")
        }

        self.facebook_request(
            path="/me",
            callback=self.async_callback(
                self._on_get_user_info, future, session, fields),
            access_token=session["access_token"],
            fields=",".join(fields)
        ) 
开发者ID:viewfinderco,项目名称:viewfinder,代码行数:21,代码来源:auth.py

示例13: test_custom_escape

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def test_custom_escape(self):
        loader = DictLoader({"foo.py":
                             "{% autoescape py_escape %}s = {{ name }}\n"})

        def py_escape(s):
            self.assertEqual(type(s), bytes_type)
            return repr(native_str(s))

        def render(template, name):
            return loader.load(template).generate(py_escape=py_escape,
                                                  name=name)
        self.assertEqual(render("foo.py", "<html>"),
                         b"s = '<html>'\n")
        self.assertEqual(render("foo.py", "';sys.exit()"),
                         b"""s = "';sys.exit()"\n""")
        self.assertEqual(render("foo.py", ["not a string"]),
                         b"""s = "['not a string']"\n""") 
开发者ID:viewfinderco,项目名称:viewfinder,代码行数:19,代码来源:template_test.py

示例14: parse_body_arguments

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def parse_body_arguments(content_type, body, arguments, files):
    """Parses a form request body.

    Supports ``application/x-www-form-urlencoded`` and
    ``multipart/form-data``.  The ``content_type`` parameter should be
    a string and ``body`` should be a byte string.  The ``arguments``
    and ``files`` parameters are dictionaries that will be updated
    with the parsed contents.
    """
    if content_type.startswith("application/x-www-form-urlencoded"):
        uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True)
        for name, values in uri_arguments.items():
            if values:
                arguments.setdefault(name, []).extend(values)
    elif content_type.startswith("multipart/form-data"):
        fields = content_type.split(";")
        for field in fields:
            k, sep, v = field.strip().partition("=")
            if k == "boundary" and v:
                parse_multipart_form_data(utf8(v), body, arguments, files)
                break
        else:
            gen_log.warning("Invalid multipart/form-data") 
开发者ID:viewfinderco,项目名称:viewfinder,代码行数:25,代码来源:httputil.py

示例15: set_status

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import native_str [as 别名]
def set_status(self, status_code, reason=None):
        """Sets the status code for our response.

        :arg int status_code: Response status code.
        :arg str reason: Human-readable reason phrase describing the status
            code. If ``None``, it will be filled in from
            `http.client.responses` or "Unknown".

        .. versionchanged:: 5.0

           No longer validates that the response code is in
           `http.client.responses`.
        """
        self._status_code = status_code
        if reason is not None:
            self._reason = escape.native_str(reason)
        else:
            self._reason = httputil.responses.get(status_code, "Unknown") 
开发者ID:tp4a,项目名称:teleport,代码行数:20,代码来源:web.py


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