How do I stop Tornado web server?

后端 未结 9 719
渐次进展
渐次进展 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'
    

提交回复
热议问题