How do I stop Tornado web server?

后端 未结 9 687
渐次进展
渐次进展 2020-12-08 06:48

I\'ve been playing around a bit with the Tornado web server and have come to a point where I want to stop the web server (for example during unit testing). The following sim

9条回答
  •  一向
    一向 (楼主)
    2020-12-08 07:43

    Here is the solution how to stop Torando from another thread. Schildmeijer provided a good hint, but it took me a while to actually figure the final example that works.

    Please see below:

    import threading
    import tornado.ioloop
    import tornado.web
    import time
    
    
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world!\n")
    
    def start_tornado(*args, **kwargs):
        application = tornado.web.Application([
            (r"/", MainHandler),
        ])
        application.listen(8888)
        print "Starting Torando"
        tornado.ioloop.IOLoop.instance().start()
        print "Tornado finished"
    
    def stop_tornado():
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.add_callback(ioloop.stop)
        print "Asked Tornado to exit"
    
    def main():
    
        t = threading.Thread(target=start_tornado)  
        t.start()
    
        time.sleep(5)
    
        stop_tornado()
        t.join()
    
    if __name__ == "__main__":
        main()
    

提交回复
热议问题