5
votes

Let's take the hello world application in the Tornado home page:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    self.write("Hello, world")

application = tornado.web.Application([
  (r"/", MainHandler),
])

if __name__ == "__main__":
  application.listen(8888)
  tornado.ioloop.IOLoop.instance().start()

Is there a way, after the IOloop has been started and without stopping it, to essentially stop the application and start another one (on the same port or on another)?

I saw that I can add new application (listening on different ports) at runtime, but I do not know how I could stop existing ones.

3

3 Answers

6
votes

Application.listen() method actually creates a HTTPServer and calls its listen() medthod. HTTPServer objects has stop() method which is probably what you need. But in order to do it you have to explicitly create HTTPServer object in your script.

server = HTTPServer(application)
server.listen(8888)
tornado.ioloop.IOLoop.instance().start()

#somewhere in your code
server.stop()
2
votes

Here is a gist about how to gracefully and safely shutdown the tornado ioloop.

https://gist.github.com/nicky-zs/6304878

However, you can refer to this implementation to achieve your goal.

2
votes

To add to @Alex Shkop's answer a few years later, as of Tornado 4.3 .listen() returns a reference to its HTTPServer!

https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.listen

server = app.listen()
... # later
server.stop()

Further, if you're working in a Jupyter notebook and for some reason need a Tornado server, you can try to close the HTTPServer before you recreate it to avoid OSError: [Errno 98] Address already in use on re-running the cell

# some Jupyter cell
#
import tornado.web

try:
    server.stop()  # NameError on first cell run
except Exception as ex:
    print(f"server not started to stop: {repr(ex)}")
else:  # did not raise NameError: server was running
    print(f"successfully stopped server: {server}")

app = tornado.web.Application(...)
server = app.listen(9006)  # arbitrary listening port