generalize connect in High Level Network Classes ?

Matt Russell matt at teaphoo.fsnet.co.uk
Thu Apr 3 08:04:16 EST 2003


Hi all,

recently i have wanted a timeout on my ftp connection using ftplib,
and have submitted a patch on sf to allow me to do this.

However, I recently came across httplib that has (almost) duplicate
code, that also would benifit from using the new timeout features in
2.3

What does anyone think of a base for these two classes?

e.g

class NetworkConnection(object):
    def settimeout(self, t):
        """Proxy method to set the timeout on the underlying socket
object"""
        try:
            float(t)
        except ValueError, e:
            raise e
        else:
            try:
                self.sock.settimeout(t)
            except AttributeError, e:
                raise Exception("Connect has not been called. pass
timeout=n to connect instead")

    def gettimeout(self):
        """Get the  timeout if any of the underlying socket object"""
        return self.sock.gettimeout()
         
    def connect(self):
        """Connect to the host and port specified in __init__."""
        msg = "getaddrinfo returns an empty list"
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                if self.debuglevel > 0:
                    print "connect: (%s, %s)" % (self.host, self.port)
                self.sock.connect(sa)
            except socket.error, msg:
                if self.debuglevel > 0:
                    print 'connect fail:', (self.host, self.port)
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg
    


Removing connect from httplib and replacing the connect method in
ftplib with

def connect(self, host, port, timeout):
    NetworkConnection.connect((host,port), timeout=timeout)
    self.af = af
    self.file = self.sock.makefile('rb')
    self.welcome = self.getresp()
    return self.welcome

Any takers?
If so will submit/revise a patch

Matt Russell




More information about the Python-list mailing list