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


Python HTTPHeaders.get_all方法代码示例

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


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

示例1: _prepare_request

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
    def _prepare_request(self, messages):

        # Determine the URL for the messages
        url = self.url
        if self._append_message_type and len(messages) == 1 and messages[0].channel.is_meta():
            message_type = '/'.join(messages[0].channel.parts()[1:])
            if not url.endswith('/'):
                url += '/'
            url += message_type

        # Get the headers for the request
        headers = HTTPHeaders()
        for header, values in self.get_headers().iteritems():
            for value in values:
                headers.add(header, value)
        for header, value in headers.get_all():
            self.log.debug('Request header %s: %s' % (header, value))

        # Get the body for the request
        body = Message.to_json(messages, encoding='utf8')
        self.log.debug('Request body (length: %d): %s' % (len(body), body))

        # Get the timeout (in seconds)
        timeout = self.get_timeout(messages) / 1000.0
        self.log.debug('Request timeout: %ss' % timeout)

        # Build and return the request
        return HTTPRequest(
            url,
            method='POST',
            headers=headers,
            body=body,
            connect_timeout=timeout,
            request_timeout=timeout
        )
开发者ID:silentsound,项目名称:baiocas,代码行数:37,代码来源:long_polling.py

示例2: write_error

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
    def write_error(self, status_code, **kwargs):
        exc_info = kwargs.pop('exc_info')
        kwargs['exception'] = exc_info[1]

        if debug:
            message = "<h4>Error Code: " + str(status_code) + "</h4>"
            message += "<h4>Error Type: " + str(exc_info[0]) + "</h4>"
            message += "<h4>Error Detail: " + str(exc_info[1]) + "</h4>"

            message += "<h4>Header:</h4>"
            message += "<br />".join(
                '%s: "%s"' % (elem[0], elem[1]) for elem in HTTPHeaders.get_all(self.request.headers))
            message += "<h4>Content:</h4>"
            message += "<br />".join(
                ['%s: "%s"' % (key, ', '.join(value)) for key, value in self.request.arguments.items()])

            if "exc_info" in kwargs:
                message += "<h4>Traceback:</h4>"
                message += "<br />".join(traceback.format_exception(*kwargs["exc_info"]))

            message = message.replace("<", "").replace(">", "")

            if status_code == 404:
                sendEmail(u"404 页面找不到", message.decode('utf-8'))
                self.render('404.html')
            elif status_code == 500:
                sendEmail(u"500 页面找不到", message.decode('utf-8'))
                # self.render('500.html')
            else:
                sendEmail(u"*** 未知异常", message.decode('utf-8'))
                tornado.web.RequestHandler.write_error(self, status_code, **kwargs)
        else:
            tornado.web.RequestHandler.write_error(self, status_code, **kwargs)
开发者ID:dreambt,项目名称:cms4p,代码行数:35,代码来源:common.py

示例3: compose_response

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
    def compose_response(self):

        headers = HTTPHeaders()

        headers = self.process_headers(headers)

        lines = []

        lines.append("HTTP/1.1 %d %s" % (
            self.response.code,
            responses[self.response.code]
        ))

        for k, v in headers.get_all():
            lines.append(k + ": " + v)

        head = "\r\n".join(lines) + "\r\n\r\n"
        head = head.encode("ascii")

        body = self.process_body(self.response.body)

        if body is not None:
            return head + self.response.body
        else:
            return head
开发者ID:ei-grad,项目名称:charon,代码行数:27,代码来源:charon.py

示例4: test_pickle_roundtrip

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
 def test_pickle_roundtrip(self):
     headers = HTTPHeaders()
     headers.add('Set-Cookie', 'a=b')
     headers.add('Set-Cookie', 'c=d')
     headers.add('Content-Type', 'text/html')
     pickled = pickle.dumps(headers)
     unpickled = pickle.loads(pickled)
     self.assertEqual(sorted(headers.get_all()), sorted(unpickled.get_all()))
     self.assertEqual(sorted(headers.items()), sorted(unpickled.items()))
开发者ID:FlorianLudwig,项目名称:tornado,代码行数:11,代码来源:httputil_test.py

示例5: test_setdefault

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
 def test_setdefault(self):
     headers = HTTPHeaders()
     headers['foo'] = 'bar'
     # If a value is present, setdefault returns it without changes.
     self.assertEqual(headers.setdefault('foo', 'baz'), 'bar')
     self.assertEqual(headers['foo'], 'bar')
     # If a value is not present, setdefault sets it for future use.
     self.assertEqual(headers.setdefault('quux', 'xyzzy'), 'xyzzy')
     self.assertEqual(headers['quux'], 'xyzzy')
     self.assertEqual(sorted(headers.get_all()), [('Foo', 'bar'), ('Quux', 'xyzzy')])
开发者ID:FlorianLudwig,项目名称:tornado,代码行数:12,代码来源:httputil_test.py

示例6: test_header_reuse

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
 def test_header_reuse(self):
     # Apps may reuse a headers object if they are only passing in constant
     # headers like user-agent.  The header object should not be modified.
     headers = HTTPHeaders({'User-Agent': 'Foo'})
     self.fetch("/hello", headers=headers)
     self.assertEqual(list(headers.get_all()), [('User-Agent', 'Foo')])
开发者ID:dkdenza,项目名称:tornado,代码行数:8,代码来源:simple_httpclient_test.py

示例7: ResponseHandler

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]

#.........这里部分代码省略.........
        self.message = message
        self.status_sent = True
        return self.stream.write(b'HTTP/1.1 '+
                utf8(denumber(code))+
                b' '+utf8(message)+b'\r\n')
    def send_header(self,name,value=None):
        if value is not None:
            self.headers.add(name,decodeHeader(name,value))
        if self.check_header(name,value): 
            del self.headers[name]
        else:
            return self.actually_send_header(name)
    needDate = True
    @gen.coroutine
    def actually_send_header(self,name):
        if self.status_sent is not True:
            if self.code:
                yield self.send_status(self.code,self.message)
            else:
                print("need to send status first!")
                raise RuntimeError('please send status')
        yield send_header(self.stream, name, self.headers[name])
        if name == 'Date':
            self.needDate = False
        del self.headers[name]
    @gen.coroutine
    def end_headers(self):
        if self.finished_headers:
            raise RuntimeError('finished headers already!')
        if not self.conn.old_client:
            self.headers.add("Connection","keep-alive")
        if self.needDate:
            yield self.send_header('Date',datetime.now())
        for name,normalized_value in self.headers.get_all():
            self.check_header(name,normalized_value)
            yield send_header(self.stream, name, normalized_value)
        if not self.chunked and self.length is None:
            if self.code in {304,204}: #...?
                assert not self.pending,"No data for these codes allowed (or length header)"
            else:
                if not self.conn.old_client:
                    length = 0
                    for chunk in self.pending:
                        # no reason to chunk, since we got all the body already
                        length += len(chunk)
                    self.headers.add("Content-Length",denumber(length))
                    yield self.actually_send_header("Content-Length")
                    self.length = length
        yield self.stream.write(b'\r\n')
        self.finished_headers = True
        yield self.flush_pending()
    @gen.coroutine
    def flush_pending(self):
        pending = self.pending
        self.pending = None
        for chunk in pending:
            yield self.write(chunk)
    written = 0
    def write(self,chunk):
        if self.pending is not None:
            self.pending.append(chunk)
            return success
        
        if self.chunked:
            chunk = self.conn._format_chunk(chunk)
        elif self.length:
开发者ID:cyisfor,项目名称:gnunet-webserver,代码行数:70,代码来源:myserver.py

示例8: write_headers

# 需要导入模块: from tornado.httputil import HTTPHeaders [as 别名]
# 或者: from tornado.httputil.HTTPHeaders import get_all [as 别名]
 def write_headers(
     self,
     start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
     headers: httputil.HTTPHeaders,
     chunk: bytes = None,
 ) -> "Future[None]":
     """Implements `.HTTPConnection.write_headers`."""
     lines = []
     if self.is_client:
         assert isinstance(start_line, httputil.RequestStartLine)
         self._request_start_line = start_line
         lines.append(utf8("%s %s HTTP/1.1" % (start_line[0], start_line[1])))
         # Client requests with a non-empty body must have either a
         # Content-Length or a Transfer-Encoding.
         self._chunking_output = (
             start_line.method in ("POST", "PUT", "PATCH")
             and "Content-Length" not in headers
             and "Transfer-Encoding" not in headers
         )
     else:
         assert isinstance(start_line, httputil.ResponseStartLine)
         assert self._request_start_line is not None
         assert self._request_headers is not None
         self._response_start_line = start_line
         lines.append(utf8("HTTP/1.1 %d %s" % (start_line[1], start_line[2])))
         self._chunking_output = (
             # TODO: should this use
             # self._request_start_line.version or
             # start_line.version?
             self._request_start_line.version == "HTTP/1.1"
             # 1xx, 204 and 304 responses have no body (not even a zero-length
             # body), and so should not have either Content-Length or
             # Transfer-Encoding headers.
             and start_line.code not in (204, 304)
             and (start_line.code < 100 or start_line.code >= 200)
             # No need to chunk the output if a Content-Length is specified.
             and "Content-Length" not in headers
             # Applications are discouraged from touching Transfer-Encoding,
             # but if they do, leave it alone.
             and "Transfer-Encoding" not in headers
         )
         # If connection to a 1.1 client will be closed, inform client
         if (
             self._request_start_line.version == "HTTP/1.1"
             and self._disconnect_on_finish
         ):
             headers["Connection"] = "close"
         # If a 1.0 client asked for keep-alive, add the header.
         if (
             self._request_start_line.version == "HTTP/1.0"
             and self._request_headers.get("Connection", "").lower() == "keep-alive"
         ):
             headers["Connection"] = "Keep-Alive"
     if self._chunking_output:
         headers["Transfer-Encoding"] = "chunked"
     if not self.is_client and (
         self._request_start_line.method == "HEAD"
         or cast(httputil.ResponseStartLine, start_line).code == 304
     ):
         self._expected_content_remaining = 0
     elif "Content-Length" in headers:
         self._expected_content_remaining = int(headers["Content-Length"])
     else:
         self._expected_content_remaining = None
     # TODO: headers are supposed to be of type str, but we still have some
     # cases that let bytes slip through. Remove these native_str calls when those
     # are fixed.
     header_lines = (
         native_str(n) + ": " + native_str(v) for n, v in headers.get_all()
     )
     lines.extend(l.encode("latin1") for l in header_lines)
     for line in lines:
         if b"\n" in line:
             raise ValueError("Newline in header: " + repr(line))
     future = None
     if self.stream.closed():
         future = self._write_future = Future()
         future.set_exception(iostream.StreamClosedError())
         future.exception()
     else:
         future = self._write_future = Future()
         data = b"\r\n".join(lines) + b"\r\n\r\n"
         if chunk:
             data += self._format_chunk(chunk)
         self._pending_write = self.stream.write(data)
         future_add_done_callback(self._pending_write, self._on_write_complete)
     return future
开发者ID:rgbkrk,项目名称:tornado,代码行数:89,代码来源:http1connection.py


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