python3上的龙卷风

时间:2014-10-25 12:26:42

标签: sockets http python-3.x tornado

我的目标是使用tornado(http://www.tornadoweb.org/)在python3上运行http服务器。 我开始在他们的网页上运行示例code

import tornado.httpserver
import tornado.ioloop

from tornado import httputil

def handle_request(request):
   message = "You requested %s\n" % request.uri
   request.connection.write_headers(
       httputil.ResponseStartLine('HTTP/1.1', 200, 'OK'),
       {"Content-Length": str(len(message))})
   request.connection.write(message)
   request.connection.finish()


http_server = tornado.httpserver.HTTPServer(handle_request)
http_server.listen(8080)
tornado.ioloop.IOLoop.instance().start()

此代码在收到任何http请求时抛出以下异常:

    ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tornado/http1connection.py", line 234, in _read_message
    delegate.finish()
  File "/usr/local/lib/python3.4/dist-packages/tornado/httpserver.py", line 280, in finish
    self.server.request_callback(self.request)
  File "test.py", line 10, in handle_request
    {"Content-Length": str(len(message))})
  File "/usr/local/lib/python3.4/dist-packages/tornado/http1connection.py", line 367, in write_headers
    lines.extend([utf8(n) + b": " + utf8(v) for n, v in headers.get_all()])
AttributeError: 'dict' object has no attribute 'get_all'

什么错了?这是示例代码,所以它应该工作,问题出现在我的环境中? 我在最新的Ubuntu和Win 7上尝试了这个,它给了我同样的错误。

提前致谢

1 个答案:

答案 0 :(得分:2)

文档中有一个错误fixed recently。对于任何版本的Python,您无法将原始字典传递给write_headers。相反,您必须将dict包装在HTTPHeaders对象中。对于Python 3,消息必须是字节实例。有两个修复:

def handle_request(request):
   message = ("You requested %s\n" % request.uri).encode('ascii')
   request.connection.write_headers(
       httputil.ResponseStartLine('HTTP/1.1', 200, 'OK'),
       httputil.HTTPHeaders({"Content-Length": str(len(message))}))
   request.connection.write(message)
   request.connection.finish()