我不知道如何在python中使用socketserver.tcpserver将变量发送到tcphandler。

HOST, PORT = hosts[0], args.port
server = SocketServer.TCPServer((HOST, PORT), METCPHandler)
server.serve_forever()

它要求:
class METCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        r = MExpressHandler(self.data, False)

但我想将调试布尔值传递给mexpresshandler。所以
HOST, PORT = hosts[0], args.port
server = SocketServer.TCPServer((HOST, PORT), METCPHandler(debug))
server.serve_forever()

失败。正确的做法是什么?我是否必须重新创建一个完整的Tcphandler over riding?

最佳答案

相信您的直觉,正确的方法确实是对tcpserver进行子类化并重写__init__方法,但是python使这非常简单!

import SocketServer

class DebugTCPServer(SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, debug=True):
        self.debug = debug
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=True)

class DebugMETCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        # self.server is an instance of the DebugTCPServer
        DEBUG = self.server.debug
        self.data = self.request.recv(1024).strip()
        if DEBUG:
            print "{} wrote:".format(self.client_address[0])
        r = MExpressHandler(self.data, False)


server = DebugTCPServer((HOST, PORT), DebugMETCPHandler, debug=True)

或者由于我们将debug=True指定为默认值:
server = DebugTCPServer((HOST, PORT), DebugMETCPHandler)

10-08 16:17