Search code examples
pythontcpsocketserver

send a variable to a TCPHandler in python


I'm confused as to how to send a variable to a TCPHandler using SocketServer.TCPServer in python..

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

Which calls:

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)

But I want to pass a debug boolean to MExpressHandler.. so

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

Fails. Whats the correct way of doing this? Do I have to recreate a whole TCPHandler over-ridding __init__?


Solution

  • Trust your instincts, the correct way is indeed to subclass TCPServer and override the __init__ method, but Python makes this very easy!

    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)
    

    or since we specified debug=True as the default:

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