How do I stop Tornado web server?

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

    There is a problem with Zaar Hai's solution, namely that it leaves the socket open. The reason I was looking for a solution to stop Tornado is I'm running unit tests against my app server and I needed a way to start/stop the server between tests to have a clear state (empty session, etc.). By leaving the socket open, the second test always ran into an Address already in use error. So I came up with the following:

    import logging as log
    from time import sleep
    from threading import Thread
    
    import tornado
    from tornado.httpserver import HTTPServer
    
    
    server = None
    thread = None
    
    
    def start_app():
        def start():
            global server
            server = HTTPServer(create_app())
            server.listen(TEST_PORT, TEST_HOST)
            tornado.ioloop.IOLoop.instance().start()
        global thread
        thread = Thread(target=start)
        thread.start()
        # wait for the server to fully initialize
        sleep(0.5)
    
    
    def stop_app():
        server.stop()
        # silence StreamClosedError Tornado is throwing after it is stopped
        log.getLogger().setLevel(log.FATAL)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.add_callback(ioloop.stop)
        thread.join()
    

    So the main idea here is to keep a reference to the HTTPServer instance and call its stop() method. And create_app() just returns an Application instance configured with handlers. Now you can use these methods in your unit tests like this:

    class FoobarTest(unittest.TestCase):
    
        def setUp(self):
            start_app()
    
        def tearDown(self):
            stop_app()
    
        def test_foobar(self):
            # here the server is up and running, so you can make requests to it
            pass
    

提交回复
热议问题