如何停止网站服务器,如何停止Tornado web服务器?

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服务器?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值