gpt4 book ai didi

sockets - python3 上的 Tornado

转载 作者:可可西里 更新时间:2023-11-01 17:09:08 25 4
gpt4 key购买 nike

我的目标是使用 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 上都试过了,它给了我同样的错误。

提前致谢

最佳答案

文档有一个错误,fixed recently .对于 任何 版本的 Python,您不能将原始字典传递给 write_headers。相反,您必须将字典包装在 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()

关于sockets - python3 上的 Tornado ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com