Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for BaseRequestHandler classes to be stateful?

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()
like image 494
Adam Lewis Avatar asked Dec 18 '11 01:12

Adam Lewis


1 Answers

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.

like image 65
alexisdm Avatar answered Sep 16 '22 19:09

alexisdm