How do I stop Tornado web server?

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

    We want to use a multiprocessing.Process with a tornado.ioloop.IOLoop to work around the cPython GIL for performance and independency. To get access to the IOLoop we need to use Queue to pass the shutdown signal through.

    Here is a minimalistic example:

    class Server(BokehServer)
    
        def start(self, signal=None):
            logger.info('Starting server on http://localhost:%d'
                        % (self.port))
    
            if signal is not None:
                def shutdown():
                    if not signal.empty():
                        self.stop()
                tornado.ioloop.PeriodicCallback(shutdown, 1000).start()
    
            BokehServer.start(self)
            self.ioloop.start()
    
        def stop(self, *args, **kwargs):  # args important for signals
            logger.info('Stopping server...')
            BokehServer.stop(self)
            self.ioloop.stop()
    

    The Process

    import multiprocessing as mp
    import signal
    
    from server import Server  # noqa
    
    class ServerProcess(mp.Process):
        def __init__(self, *args, **kwargs):
            self.server = Server(*args, **kwargs)
            self.shutdown_signal = _mp.Queue(1)
            mp.Process.__init__(self)
    
            signal.signal(signal.SIGTERM, self.server.stop)
            signal.signal(signal.SIGINT, self.server.stop)
    
        def run(self):
            self.server.start(signal=self.shutdown_signal)
    
        def stop(self):
            self.shutdown_signal.put(True)
    
    if __name__ == '__main__':
        p = ServerProcess()
        p.start()
    

    Cheers!

提交回复
热议问题