With python socketserver how can I pass a variable to the constructor of the handler class

Viewed 13461

I would like to pass my database connection to the EchoHandler class, however I can't figure out how to do that or access the EchoHandler class at all.


class EchoHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        print self.client_address, 'connected'

if __name__ == '__main__':
    conn = MySQLdb.connect (host = "10.0.0.5", user = "user", passwd = "pass", db = "database")

    SocketServer.ForkingTCPServer.allow_reuse_address = 1

    server = SocketServer.ForkingTCPServer(('10.0.0.6', 4242), EchoHandler)

    print "Server listening on localhost:4242..."
    try:
        server.allow_reuse_address
        server.serve_forever()
    except KeyboardInterrupt:
        print "\nbailing..."
5 Answers

I was currently solving same problem, but I used slightly different solution, I feel it's slightly nicer and more general (inspired by @aramaki).

In the EchoHandler you just need to overwrite __init__ and specify custom Creator method.

class EchoHandler(SocketServer.StreamRequestHandler):
    def __init__(self, request, client_address, server, a, b):
        self.a = a
        self.b = b
        # super().__init__() must be called at the end
        # because it's immediately calling handle method
        super().__init__(request, client_address, server)

    @classmethod
    def Creator(cls, *args, **kwargs):
        def _HandlerCreator(request, client_address, server):
            cls(request, client_address, server, *args, **kwargs)
        return _HandlerCreator

Then you can just call the Creator method and pass anything you need.

SocketServer.ForkingTCPServer(('10.0.0.6', 4242), EchoHandler.Creator(0, "foo"))

Main benefit is, that this way you are not creating any more instances than necessary and you are extending the class in more manageable way - you don't need to change the Creator method ever again.

It seems that you can't use ForkingServer to share variables because Copy-on-Write happens when a process tries to modify a shared variable. Change it to ThreadingServer and you'll be able to share global variables.

Related