繁体   English   中英

从Tornado中的服务器向客户端写入Content-Length标头

[英]Writing the Content-Length header to the client from the server in Tornado

我有一个龙卷风服务器,只是打印客户端发送的标头。 server.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相同数量的数据? 如果是这样,为什么以及如何做到这一点? 提前致谢。

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

从它的外观来看,你不会为回应主体写任何东西 ; 如果你说你发送len(str(message))字节,你可能也想发送str(message)

request.connection.write(str(message))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM