Search code examples
pythontornado

Stopping a tornado application


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.


Solution

  • 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()