【问题标题】:Writing the Content-Length header to the client from the server in Tornado在 Tornado 中从服务器向客户端写入 Content-Length 标头
【发布时间】:2015-01-26 08:26:24
【问题描述】:

我有一个龙卷风服务器,它只是打印客户端发送的标头。 服务器.py:

import tornado.httpserver
import tornado.ioloop
import tornado.httputil as hutil

def handle_request(request):

    message = ""
    try :
            message = request.headers['Content-Length']
    except KeyError :
            message = request.headers
    request.connection.write_headers(
            tornado.httputil.ResponseStartLine('HTTP/1.1', 200, 'OK'),
            tornado.httputil.HTTPHeaders
            ({"Content-Length": str(len(message))}))
    request.connection.finish()
    print(request.headers)

http_server = tornado.httpserver.HTTPServer(handle_request)
http_server.listen(8888, address='127.0.0.1')
tornado.ioloop.IOLoop.instance().start()

当我使用 curl 向该服务器发送请求时,我得到以下回溯。

ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 234, in _read_message
    delegate.finish()
  File "/usr/local/lib/python2.7/dist-packages/tornado/httpserver.py", line 280, in finish
    self.server.request_callback(self.request)
  File "Tests/tornado_server.py", line 17, in handle_request
    request.connection.finish()
  File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 430, in finish
    self._expected_content_remaining)
HTTPOutputError: Tried to write 5 bytes less than Content-Length

我从 Curl 发送的标头:

{'Host': '127.0.0.1:8888', 'Accept': '*/*', 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36'}

是否有必要写回与 Content-Length 相同数量的数据?如果是这样,为什么以及如何做到这一点? 提前致谢。

【问题讨论】:

    标签: python http http-headers tornado


    【解决方案1】:

    您需要写回与您说的相同数量的字节。您为 response 返回了 Content-Length 标头。这意味着您的响应 body 需要包含那么多字节。

    从外观上看,您不会为响应正文写回任何内容;如果您声明要发送 len(str(message)) 字节,您可能也想发送 str(message)

    request.connection.write(str(message))
    

    这与请求中的Content-Length分开,表示请求正文包含多少字节。

    【讨论】:

    • 谢谢!还有另一个错误,标题应该是 {"Content-Length": str(len(str(message)))}
    • @Sentient07:是的,我对 Tornado 并不那么熟悉;如果HTTPHeaders 对象不自动为您将值转换为字符串,那么您确实需要明确地执行此操作。
    • 另请注意,Tornado 会在大多数情况下为您设置 Content-Length,因此您不必自己设置。如果您正在流式传输响应(即调用 self.flush())并且您希望客户端知道下载的大小而不是使用分块编码,则只需显式设置 Content-Length。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多