Python 3 龙卷风网站

Python 3 Tornado website

我正在尝试使用 Tornado 创建一个简单的本地网站。当我 运行 并转到 http://localhost:8888 时,我收到以下错误:无法访问此站点 localhost 拒绝连接。我仍然是 python 的初学者,因此非常感谢任何帮助。我的代码如下所示。

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<!DOCTYPE html><head><title>" + "Hello world</title></head>" + "<body>Hello World</body>")

    if __name__ == "__main__":
        application = tornado.web.Application([(r"/", MainHandler),
                                               ],)
        application.listen(8888)
        tornado.ioloop.IOLOOP.instance().start()

IOLOOP 应该是 IOLoop:

tornado.ioloop.IOLoop.instance().start()
#              ^^^^^


UPDATE 您需要正确缩进代码。特别是 if __name__ == "__main__": 部分,该部分应该在 class .. 定义之外:

if __name__ == "__main__":  # <----
    application = tornado.web.Application([(r"/", MainHandler),
                                           ],)
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()