我正在尝试学习如何使用python web框架Tornado。我已经熟悉了烧瓶,但到目前为止,我甚至难以开始使用简单的应用程序。我的目录结构如下:
我在app.py中的代码很简单:
define("port", default=5000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
)
super(Application, self).__init__(handlers, **settings)
class MainHandler(tornado.web.RedirectHandler):
def get(self):
self.render("Testing.html")
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
然而,当我运行app.py时出现错误:
ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
File "/vt/release/dist/3p/anaconda/lib/python2.7/site-packages/tornado/http1connection.py", line 238, in _read_message
delegate.finish()
File "/vt/release/dist/3p/anaconda/lib/python2.7/site-packages/tornado/httpserver.py", line 289, in finish
self.delegate.finish()
File "/vt/release/dist/3p/anaconda/lib/python2.7/site-packages/tornado/web.py", line 2047, in finish
self.execute()
File "/vt/release/dist/3p/anaconda/lib/python2.7/site-packages/tornado/web.py", line 2067, in execute
**self.handler_kwargs)
File "/vt/release/dist/3p/anaconda/lib/python2.7/site-packages/tornado/web.py", line 187, in __init__
self.initialize(**kwargs)
TypeError: initialize() takes at least 2 arguments (1 given)
这是为什么?我应该提一下,在我尝试连接之前,它不会给我错误。
答案 0 :(得分:3)
您的MainHandler应该继承自RequestHandler,而不是RedirectHandler。
(详细信息:RedirectHandler需要两个参数," self"和" target_path"。您在Application .__ init__中的处理程序列表中指定目标路径。既然你如果在处理程序列表中没有第二个参数,并且您从RedirectHandler继承错误,则Tornado会获得异常。)