import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
一旦调用tornado.ioloop.IOLoop.instance().start(),它就会阻塞程序(或当前线程)。阅读IOLoop对象的source code给出了stop函数文档中的这个示例:To use asynchronous methods from otherwise-synchronous code (such as
unit tests), you can start and stop the event loop like this:
ioloop = IOLoop()
async_method(ioloop=ioloop, callback=ioloop.stop)
ioloop.start()
ioloop.start() will return after async_method has run its callback,
whether that callback was invoked before or after ioloop.start.
但是,我不知道如何将它集成到我的程序中。实际上,我有一个类封装了web服务器(它有自己的start和stop函数),但是只要我调用start,程序(或测试)当然会阻塞。
我试图在另一个进程中启动web服务器(使用multiprocessing包)。这是包装web服务器的类:class Server:
def __init__(self, port=8888):
self.application = tornado.web.Application([ (r"/", Handler) ])
def server_thread(application, port):
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(port)
tornado.ioloop.IOLoop.instance().start()
self.process = Process(target=server_thread,
args=(self.application, port,))
def start(self):
self.process.start()
def stop(self):
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_callback(ioloop.stop)
但是,停止似乎并不能完全停止web服务器,因为它仍在下一个测试中运行,即使使用此测试设置:def setup_method(self, _function):
self.server = Server()
self.server.start()
time.sleep(0.5) # Wait for web server to start
def teardown_method(self, _function):
self.kstore.stop()
time.sleep(0.5)
如何在Python程序中启动和停止Tornado web服务器?