Search code examples
pythondjangopython-3.xtornado

issue in setting up tornado.web.Application


In tornado (python) instead of creating an instance of tornado.web.Application(), I tried to make changes in the class while calling it using init.

import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import os.path


from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html", page_title="My Bookstore | HOME", header_text="Welcome to My Bookstore!")


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
        )
        tornado.web.Application(self, handlers, **settings)


if __name__ == "__main__":
    tornado.options.parse_command_line()
    #Note: not creating an instance of application here ('app'), just creating a list of handlers and a dict of settings and passing it to the superclass.
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

But I'm getting this error,

Traceback (most recent call last):
  File "main.py", line 44, in <module>
    http_server = tornado.httpserver.HTTPServer(Application())
  File "main.py", line 27, in __init__
    tornado.web.Application(self, handlers, **settings)
  File "C:\Python\Python37\lib\site-packages\tornado\web.py", line 2065, in __init__
    handlers = list(handlers or [])
TypeError: 'Application' object is not iterable

What is the error, and how can I solve it?


Solution

  • You should call super when you initialize a subclass and want to use the parent class's __init__

    This

    tornado.web.Application(self, handlers, **settings)
    

    Should be

    super().__init__(handlers, **settings)