python - 在 Tornado 中将 Content-Length header 从服务器写入客户端

标签 python http http-headers tornado

我有一个 Tornado 服务器,它只打印客户端发送的 header 。 服务器.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 发送的 header :

{'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 相同数量的数据?如果是这样,为什么以及应该如何做? 提前致谢。

最佳答案

您需要写回与您所说的相同的字节数。您为响应 返回了一个Content-Length header 。这意味着您的响应正文 需要包含那么多字节。

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

request.connection.write(str(message))

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

关于python - 在 Tornado 中将 Content-Length header 从服务器写入客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28146700/

相关文章:

字典中的 Python 打印元素产生错误

python - 在python中使用 map 不一致

python - 通过 HTTP POST 传递二进制文件

node.js - TypeScript 在 Express 中添加自定义请求 header

java - android 1.6 httpresponse 不包含位置 header

c# - 如果发生异常,"Content-encoding" header 将从 HttpHandler 响应中消失

python - pip升级后无法安装numpy

python - PYODBC 中的函数序列错误

php - Laravel Guzzle Http Auth 不起作用

http - 服务例如状态代码响应