Python Tornado – 如何修复'URLhandler需要X个参数'错误?
这里是错误信息:
TypeError: __init__() takes exactly 1 argument (3 given)
ERROR:root:Exception in callback <tornado.stack_context._StackContextWrapper object at 0x1017d4470>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/tornado-2.4.1-py2.7.egg/tornado/ioloop.py", line 421, in _run_callback
callback()
File "/Library/Python/2.7/site-packages/tornado-2.4.1-py2.7.egg/tornado/iostream.py", line 311, in wrapper
callback(*args)
File "/Library/Python/2.7/site-packages/tornado-2.4.1-py2.7.egg/tornado/httpserver.py", line 268, in _on_headers
self.request_callback(self._request)
File "/Library/Python/2.7/site-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 1395, in __call__
handler = spec.handler_class(self, request, **spec.kwargs)
TypeError: __init__() takes exactly 1 argument (3 given)
这是我的代码:
class IndexHandler(tornado.web.RequestHandler):
def __init__(self):
self.title = "Welcome!"
def get(self):
self.render("index.html", title=self.title)
我把代码简化成了上面的样子,但我搞不懂为什么会出现这个错误。我一定是哪里做错了,但我完全不知道是什么问题(传了3个参数??...呃?)
注意:title
变量只是我在 index.html 模板中的 <title>{{ title }}</title>
。
我在使用 Python 2.7.3 的 32 位版本,这样可以和 Mysqldb-Python 一起工作。正如你所看到的,我的 Tornado 版本是 2.4.1。我还在使用 OSX Lion(这会有影响吗...)也许是兼容性问题导致了这个错误?
非常感谢大家在调试这个问题时提供的帮助。
2 个回答
1
你在不合适的地方重写了
__init__()
。
可以查看
http://www.tornadoweb.org/documentation/web.html
这个文档。
它的格式是
class tornado.web.RequestHandler(application, request, **kwargs)[source]
。这说明你需要为派生类的构造函数提供相同的接口。
9
@宇宙公主说得对,但可能需要稍微详细解释一下。
Tornado会用参数application, request, **kwargs
来调用RequestHandler
子类的__init__
方法,所以你需要考虑到这一点。
你可以这样做:
def __init__(self, application, request, **kwargs):
self.title = "Welcome!"
super(IndexHandler, self).__init__(application, request, **kwargs)
这意味着你的IndexHandler
类现在的初始化方式和父类是一样的。
不过,我更推荐使用Tornado提供的initialize
方法,专门用来处理这个问题:
def initialize(self):
self.title = "Welcome!"