本文介绍了如何在BaseHTTPRequestHandler子类中停止BaseHTTPServer.serve_forever()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个单独的线程中运行我的 HTTPServer (使用无法停止线程的线程模块......)并且想要在主线程中停止提供请求线程也会关闭。

I am running my HTTPServer in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.

Python文档声明 BaseHTTPServer.HTTPServer 是 SocketServer.TCPServer ,它支持 shutdown 方法,但 HTTPServer 中缺少该方法。

The Python documentation states that BaseHTTPServer.HTTPServer is a subclass of SocketServer.TCPServer, which supports a shutdown method, but it is missing in HTTPServer.

整个 BaseHTTPServer 模块的文档很少:(

The whole BaseHTTPServer module has very little documentation :(

推荐答案

我应该首先说我可能不会自己这样做,但我过去也有。serve_forever(来自SocketServer.py)方法看起来像这样:

I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:

def serve_forever(self):
    """Handle one request at a time until doomsday."""
    while 1:
        self.handle_request()

你可以替换(在子类)而1 使用而self.should_be_running ,并从其他线程修改该值。类似于:

You could replace (in subclass) while 1 with while self.should_be_running, and modify that value from a different thread. Something like:

def stop_serving_forever(self):
    """Stop handling requests"""
    self.should_be_running = 0
    # Make a fake request to the server, to really force it to stop.
    # Otherwise it will just stop on the next request.
    # (Exercise for the reader.)
    self.make_a_fake_request_to_myself()

编辑:我挖出了当时使用的实际代码:

I dug up the actual code I used at the time:

class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):

    stopped = False
    allow_reuse_address = True

    def __init__(self, *args, **kw):
        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
        self.register_function(lambda: 'OK', 'ping')

    def serve_forever(self):
        while not self.stopped:
            self.handle_request()

    def force_stop(self):
        self.server_close()
        self.stopped = True
        self.create_dummy_request()

    def create_dummy_request(self):
        server = xmlrpclib.Server('http://%s:%s' % self.server_address)
        server.ping()

这篇关于如何在BaseHTTPRequestHandler子类中停止BaseHTTPServer.serve_forever()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 08:46