Python Tornado - 如何修复'URLhandler正好接受X参数'错误?

Joh*_*ing 4 python tornado

这是错误:

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)
Run Code Online (Sandbox Code Playgroud)

以下是代码:

class IndexHandler(tornado.web.RequestHandler):
    def __init__(self):
        self.title = "Welcome!"

    def get(self):
        self.render("index.html", title=self.title)
Run Code Online (Sandbox Code Playgroud)

我把代码简化为上面的代码,我很困惑为什么会产生这个错误.我一定做错了什么,但我不知道是什么(3个论点通过了......呃?)

注意:该title变量仅仅是<title>{{ title }}</title>我的index.html模板中的变量.

我正在运行32位版本的Python 2.7.3,以便使用Mysqldb-Python.如您所见,我的Tornado版本是2.4.1.我也在OSX Lion上运行(如果这有什么不同......)可能是兼容性问题,最终会产生这个错误?

在调试时,所有帮助都很受欢迎.谢谢.

Col*_*ean 9

@Princess of the Universe是对的,但也许这需要一些细节.

龙卷风是要调用__init__RequestHandler带有参数的子类application, request, **kwargs,所以你需要允许这一点.

你可以这样做:

def __init__(self, application, request, **kwargs):
    self.title = "Welcome!"
    super(IndexHandler, self).__init__(application, request, **kwargs)
Run Code Online (Sandbox Code Playgroud)

这意味着您的IndexHandler类现在使用与父类相同的签名进行初始化.

但是,我赞成initializeTornado为此目的提供的方法:

def initialize(self):
    self.title = "Welcome!"
Run Code Online (Sandbox Code Playgroud)

  • Tornado没有关于`RequestHandler .__ init__`的公开文档,因此没有向后兼容性合同.我认为`initialize`是唯一有效的方法,至少现在. (4认同)