我有一个龙卷风服务器,它只打印客户端发送的标头。 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相同数量的数据?如果是这样,为什么以及如何做到这一点? 提前谢谢。
答案 0 :(得分:3)
您需要回写与您所说的相同数量的字节。您为响应返回了Content-Length
标头。这意味着你的响应 body 需要包含那么多字节。
根据它的外观,你不会为反应机构写回任何;如果你说你要发送len(str(message))
字节,你可能也想发送str(message)
:
request.connection.write(str(message))
这与请求中的Content-Length
分开,表示请求正文包含的字节数。