Multiple modules with database access + general app design?

Frank Millman frank at chagford.com
Fri Jan 20 01:34:21 EST 2006


Daniel Dittmar wrote:
> Robin Haswell wrote:
> > Ah I see.. sounds interesting. Is it possible to make any module variable
> > local to a thread, if set within the current thread?
>
> Not directly. The following class tries to simulate it (only in Python 2.4):
>
> import threading
>
> class ThreadLocalObject (threading.local):

Daniel, perhaps you can help me here.

I have subclassed threading.Thread, and I store a number of attributes
within the subclass that are local to the thread. It seems to work
fine, but according to what you say (and according to the Python docs,
otherwise why would there be a 'Local' class) there must be some reason
why it is not a good idea. Please can you explain the problem with this
approach.

Briefly, this is what I am doing.

class Link(threading.Thread):  # each link runs in its own thread
    """Run a loop listening for messages from client."""

    def __init__(self,args):
        threading.Thread.__init__(self)
        print 'link connected',self.getName()
        self.ctrl, self.conn = args
        self._db = {}  # to store db connections for this client
connection
        [create various other local attributes]

    def run(self):
        readable = [self.conn.fileno()]
        error = []
        self.sendData = []  # 'stack' of replies to be sent

        self.running = True
        while self.running:
            if self.sendData:
                writable = [self.conn.fileno()]
            else:
                writable = []
            r,w,e = select.select(readable,writable,error,0.1)  # 0.1
timeout
            [continue to handle connection]

class Controller(object):
    """Run a main loop listening for client connections."""

    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((HOST,PORT))
        self.s.listen(5)
        self.running = True

    def mainloop(self):
        while self.running:
            try:
                conn,addr = self.s.accept()
                Link(args=(self,conn)).start()  # create thread to
handle connection
            except KeyboardInterrupt:
                self.shutdown()

Controller().mainloop()

TIA

Frank Millman




More information about the Python-list mailing list