覆盖 BaseHTTPRequestHandlerClass

Override BaseHTTPRequestHandlerClass

我正在设置我的第一个 HTTP 服务器来存储 POST 请求。我的处理程序 class BaseHTTPRequestHandler 有问题。 在我的方法中,我想将响应代码传递给处理程序,我希望服务器响应客户端(自动测试目的)。我在这里找到了很多帮助,我将在下面分享我开发的 subclass 所关注的代码,但我仍然需要弄清楚如何初始化我的处理程序,因为我不知道在哪里获取参数:"request"、"client_address" 和 "server"。 我在各自的位置打了三个问号。 感谢您的帮助,对于错误的解释深表歉意。

class ServerHandler(BaseHTTPRequestHandler):

    def __init__(self, response_code, request, client_address, server):
        super().__init__(request, client_address, server)
        self.response_code = response_code

    def _set_header(self):
        self.send_response(self.response_code)
        self.send_header('content-type', 'text/html')
        self.end_headers()

    def do_HEAD(self):
        self._set_header()

    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD': 'POST'}
        )

        # get POST data
        utc = int(form.getvalue("utc"))
        value = form.getvalue("value")
        sn = form.getvalue("sn")

        # manage data
        dataManager(utc, sn, value)

        # send response
        self._set_header()
        response = "<RESULT>0</RESULT>"
        self.wfile.write(response.encode('utf-8'))


class Server:

    def __init__(self, port, response_code=200, server_class=HTTPServer):
        self.port = port
        self.response_code = response_code
        self.server_address = ('', self.port)
        handler_class = ServerHandler(self.response_code, ?, ?, ?)
        self.server = server_class(self.server_address, handler_class)
        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True

    def run(self):
        self.server_thread.start()
        print("Server started")

    def shutdown(self):
        self.server.shutdown()
        self.server.server_close()
        print("Server stopped")

我解决了以下问题。我没有将 response_code 作为函数参数传递,而是将 response_code 添加为 class 变量,并从 class 服务器直接写入 public class变量response_code。而已。不是最好的解决方案,但它有效。如果您有更好的想法,请告诉我。

class ServerHandler(BaseHTTPRequestHandler):

def __init__(self, request, client_address, server):
    super().__init__(request, client_address, server)
    self.response_code = response_code

def _set_header(self):
    self.send_response(self.response_code)
    self.send_header('content-type', 'text/html')
    self.end_headers()

def do_HEAD(self):
    self._set_header()

def do_POST(self):
    form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={'REQUEST_METHOD': 'POST'}
    )

    # get POST data
    utc = int(form.getvalue("utc"))
    value = form.getvalue("value")
    sn = form.getvalue("sn")

    # manage data
    dataManager(utc, sn, value)

    # send response
    self._set_header()
    response = "<RESULT>0</RESULT>"
    self.wfile.write(response.encode('utf-8'))  

class Server:

def __init__(self, port, response_code=200, server_class=HTTPServer):
    self.port = port
    self.server_address = ('', self.port)
    handler_class = ServerHandler
    handler_class.response_code = response_code
    self.server = server_class(self.server_address, handler_class)
    self.server_thread = threading.Thread(target=self.server.serve_forever)
    self.server_thread.daemon = True

def run(self):
    self.server_thread.start()
    print("Server started")

def shutdown(self):
    self.server.shutdown()
    self.server.server_close()
    print("Server stopped")