5

Short Question
Using my examples below, is there a Pythonic way to share my_object's actual instance with with the BaseRequestHandler class?

Background
By definition, the BaseRequestHandler class creates a new instance for each request. Because of this, I am struggling to try find a solution on how to get data from the handle() function back to the ProtocolInterface instance. Note that this might be the wrong approach if I am needing to do something in handle() other than print to stdout.

At this point in time, I do not believe that global variables will work because my_object is passed in and is expected to change often (this is why handle() needs to see it. To see an example client (sending bogus data) see my other SO question. I think the biggest issue I am facing is the the socketservers are running in a background thread.

Example of what I would like to do

class ProtocolHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while(1):
            self.data = self.request.recv(1024)
            if self.data == '':
                break
            self.request.send("Success") 
            self.my_object.success = True#  <--- How can I share my_object's instance?

class ProtocolInterface():
    def __init__(self, obj, host='127.0.0.1', port=8000, single_connection=False):
        self.my_object = obj # <--- This ideally is the same instance seen in ProtocolHandler
        self.host = host
        self.port = port

        # Create the socket server to process in coming traffic
        if(single_connection):
            self.server = SocketServer.TCPServer((self.host, self.port), ProtocolHandler)
        else:
            self.server = SocketServer.ThreadingTCPServer((self.host, self.port), ProtocolHandler)

    def start(self):
        print "Server Starting on HOST: " + self.host
        server_thread = threading.Thread(target=self.server.serve_forever)
        server_thread.daemon = True
        server_thread.start()
Cœur
  • 37,241
  • 25
  • 195
  • 267
Adam Lewis
  • 7,017
  • 7
  • 44
  • 62

1 Answers1

8

You could pass the object through the server instance:

self.server = SocketServer.TCPServer((self.host, self.port), ProtocolHandler)
self.server.my_object = self.my_object

The documentation indicates that you can have access to the server instance in handle() as self.server.

alexisdm
  • 29,448
  • 6
  • 64
  • 99
  • 1
    Wish I would have seen that. Works like a champ. Thanks! – Adam Lewis Dec 18 '11 at 03:35
  • How is this useful without thread synchronization? Multiple threads are writing to the same variable. How is the server object supposed to use or make sense of it? – Francis Avila Dec 19 '11 at 20:15
  • @FrancisAvila: The object you expose to the base clients would have to be thread safe / implement locking. My example code above was admittedly poorly written just using a bool. A threading.Event with the set/clear methods would have been a better example. – Adam Lewis Jun 25 '14 at 13:58