Saturday, March 28, 2009

kdbom.tryDBconnect

I put a factory function for kdbom.db instances in kdbom.kdbom (previously I had it in viroinfo).

It automatically checks localhost,3306 for the database after checking at the specified sites.... good if clients are not on the same private subnet the the server is on.



def tryDBconnect(db=None,serversPorts=None,user=None,
reuseDB=None,getTables=True,tryLocalPort=3306,
fatal=False,verboseFailure=False):
"""Try to connect to a database and return the db instance. One or more server/port
combinations can be tried. If no connection is successful a Warning is issued,
unless fatal is true in which case KdbomDatabaseError is raised.

db = databse name (string)
server = servers hostname (string)
port = server's listening port (int)

After all given (server,port) combinations are tried one or more localhost
connections over port tryLocalPort will be attempted unless that is set
to None. tryLocalPort can be an integre type or a sequence of integers.

serversPorts should be a list of (server,port) tuples, or a single 2-tuple.
serversPorts can also be a single string to make replacement of db()
calls more straight forward (defaultPort is then used for the port).

Ir reuseDB is specified, this is just a call to the db class constructor.
"""

connected = False
database = None

if reuseDB != None:
database = kdbom.db(db=db,reuseDBconnection=reuseDB,getTables=getTables)
connected = True
else:
if type (serversPorts) in StringTypes:
serversPorts = [(serversPorts,defaultPort)]
if type(serversPorts) != ListType:
if type(serversPorts) == NoneType:
serversPorts = []
elif (len(serversPorts) == 2
and type(serversPorts[0]) in StringTypes
and type(serversPorts[1]) in (IntType,LongType)):
serversPorts = [serversPorts]
elif type(serversPorts) == TupleType:
serversPorts = [serversPorts]
else:
raise ArgumentError, "serversPorts should be a list of tuples not: %s" % serversPorts
try:
for p in tryLocalPort:
serversPorts.append(('localhost',p))
except TypeError:
serversPorts.append(('localhost',tryLocalPort))

for host,port in serversPorts:
try:
print host,port
database = kdbom.db(db=db,host=host,port=port,user=user,getTables=getTables)
connected = True
except:
pass

if not connected:
if fatal:
if not verboseFailure:
raise KdbomDatabaseError, "%s DB not loaded" % db

else:
warnings.warn("%s DB not loaded" % db)
return database

No comments:

Post a Comment