通过HTTP停止cherrypy服务器

6 投票
2 回答
3062 浏览
提问于 2025-04-15 18:23

我有一个用cherrypy搭建的应用程序,通过wxpython的界面来控制它。我想在界面关闭的时候把服务器也关掉,但我不知道该怎么做。目前我只是简单地在窗口关闭事件中使用了sys.exit(),但是这样会导致

Traceback (most recent call last):
  File "ui.py", line 67, in exitevent
    urllib.urlopen("http://"+server+"/?sigkill=1")
  File "c:\python26\lib\urllib.py", line 87, in urlopen
    return opener.open(url)
  File "c:\python26\lib\urllib.py", line 206, in open
    return getattr(self, name)(url)
  File "c:\python26\lib\urllib.py", line 354, in open_http
    'got a bad status line', None)
IOError: ('http protocol error', 0, 'got a bad status line', None)

这是因为我没有正确地停止cherrypy吗?

2 个回答

3

我使用了 os._exit。并且我把它放在一个线程里,这样我可以在退出之前显示一个“你已经退出服务器”的页面。

class MyApp(object):
    @cherrypy.expose
    def exit(self):
        """
        /exit
        Quits the application
        """

        threading.Timer(1, lambda: os._exit(0)).start()
        return render("exit.html", {})
10

你是怎么停止CherryPy的?是给它自己发个SIGKILL信号吗?其实你至少应该发个TERM信号,更好的做法是调用 cherrypy.engine.exit()(版本3.1及以上)。这两种方法都能让CherryPy更优雅地关闭,这样可以让正在处理的请求(比如你发的那个"?sigkill=1"请求)完成并正常结束。

撰写回答