Search code examples
pythonpython-3.xflasktornado

Tornado : support multiple Applications when using multi-process?(NOTE:multiple Applications)


Here is my code.

application1 = web.Application([
    (r"/", MainPageHandler),
])
http_server = httpserver.HTTPServer(application1)
http_server.listen(8080)

application2 = web.Application([
    (r"/appli2", MainPageHandler2),
])
http_server2 = httpserver.HTTPServer(application2)
http_server2.listen(8081)

ioloop.IOLoop.instance().start()

I want to use multi-process like https://www.tornadoweb.org/en/stable/httpserver.html. What should I modify my codes?


Solution

  • To support multiple Applications with multi-process mode, you must use the "advanced" mode with the add_sockets method:

    sockets1 = tornado.netutil.bind_sockets(8080)
    sockets2 = tornado.netutil.bind_sockets(8081)
    tornado.process.fork_processes(0)
    server1 = HTTPServer(app1)
    server2 = HTTPServer(app2)
    server1.add_sockets(sockets1)
    server2.add_sockets(sockets2)
    IOLoop.current().start()
    

    Bind all the sockets (and do nothing else) before the call to fork_processes, then create the servers and add the sockets to them.