How do I stop Tornado web server?

后端 未结 9 672
渐次进展
渐次进展 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:41

    Tornado's IOloop.instance() has trouble stopping from an external signal when run under multiprocessing.Process.

    The only solution I came up with that works consistently, is by using Process.terminate():

    import tornado.ioloop, tornado.web
    import time
    import multiprocessing
    
    class Handler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")
    
    application = tornado.web.Application([ (r"/", Handler) ])
    
    class TornadoStop(Exception):
        pass
    def stop():
        raise TornadoStop
    class worker(multiprocessing.Process):
        def __init__(self):
            multiprocessing.Process.__init__(self)
            application.listen(8888)
            self.ioloop = tornado.ioloop.IOLoop.instance()
    
        def run(self):
            self.ioloop.start()
    
        def stop(self, timeout = 0):
            self.ioloop.stop()
            time.sleep(timeout)
            self.terminate()
    
    
    
    if __name__ == "__main__":
    
        w = worker()
        print 'starting server'
        w.start()
        t = 2
        print 'waiting {} seconds before stopping'.format(t)
        for i in range(t):
            time.sleep(1)
            print i
        print 'stopping'
        w.stop(1)
        print 'stopped'
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2020-12-08 07:49

    Just add this before the start():

    IOLoop.instance().add_timeout(10,IOLoop.instance().stop)

    It will register the stop function as a callback in the loop and lauch it 10 second after the start

    0 讨论(0)
提交回复
热议问题