commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnue] r7804 - trunk/gnue-common/src/datasources


From: reinhard
Subject: [gnue] r7804 - trunk/gnue-common/src/datasources
Date: Tue, 9 Aug 2005 12:02:35 -0500 (CDT)

Author: reinhard
Date: 2005-08-09 12:02:34 -0500 (Tue, 09 Aug 2005)
New Revision: 7804

Modified:
   trunk/gnue-common/src/datasources/GConnections.py
   trunk/gnue-common/src/datasources/GLoginHandler.py
   trunk/gnue-common/src/datasources/readgsd.py
Log:
Cleanup, docstrings, comments. While I was at it, also fixed the bug that made
all gnue applications ignore --username and --password command line parameters.


Modified: trunk/gnue-common/src/datasources/GConnections.py
===================================================================
--- trunk/gnue-common/src/datasources/GConnections.py   2005-08-08 21:41:12 UTC 
(rev 7803)
+++ trunk/gnue-common/src/datasources/GConnections.py   2005-08-09 17:02:34 UTC 
(rev 7804)
@@ -20,13 +20,8 @@
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
 # $Id$
-
 """
-Class that loads connection definition files and maintains
-database connections.
-
-If you pass GConnections an "eventHandler" instance, it will generate a
-Connections:Connect(name, base) when a new connection is created.
+Connection manager system.
 """
 
 from ConfigParser import *
@@ -43,22 +38,25 @@
 # Exceptions
 # =============================================================================
 
-class Error(errors.gException):
-  # Base error
-  pass
+class NotFoundError (errors.AdminError):
+  """
+  Connection name not found in connections.conf.
+  """
+  def __init__ (self, name, file):
+    msg = u_("The connections file does not contain a definition "
+             "for \"%(connection)s\".\n\nFile: %(file)s") \
+           % {'connection': name,
+              'file'      : file}
+    errors.AdminError.__init__ (self, msg)
 
-class NotFoundError (Error):
-  # Raised if a requested connection name does not
-  # exist in the Connections Definition File.
-  pass
+# -----------------------------------------------------------------------------
 
-class AdapterNotInstalled (errors.AdminError):
-  # Raised if a provider is requested for which
-  # the python libraries are not installed.
-  pass
+class DependencyError (errors.AdminError):
+  """
+  Cannot load database driver plugin due to a missing dependency.
 
-class DependencyError (errors.AdminError):
-  # Raised by the dbdrivers if a dependency module is missing
+  This exception is raised by the database drivers.
+  """
   def __init__ (self, modulename, url):
     self.modulename = modulename
     self.url = url
@@ -67,11 +65,16 @@
       message += u_("  You can download it from %s.") % self.url
     errors.AdminError.__init__ (self, message)
 
+# -----------------------------------------------------------------------------
+
 class InvalidFormatError (errors.AdminError):
-  # Raised if the Connections Definition File is
-  # in an unreadable format.
+  """
+  Cannot parse connections.conf file.
+  """
   pass
 
+# -----------------------------------------------------------------------------
+
 LoginError = Exceptions.LoginError
 
 
@@ -80,26 +83,60 @@
 # =============================================================================
 
 class GConnections:
+  """
+  Class that loads connection definition files and maintains
+  database connections.
 
+  If you pass GConnections an "eventHandler" instance, it will generate a
+  Connections:Connect(name, base) when a new connection is created.
+  """
+
   # ---------------------------------------------------------------------------
   # Constructor
   # ---------------------------------------------------------------------------
 
-  def __init__(self, location, loginHandler=None, loginOptions={},
-               eventhandler=None):
+  def __init__ (self, location, loginHandler = None, loginOptions = {},
+                eventhandler = None):
+    """
+    Create a new GConnections instance.
 
+    @param location: Filename of the connections.conf file.
+    @param loginHandler: Instance of a L{GLoginHandler.GLoginHandler}
+      descendant to ask the user for login data.
+    @param loginOptions: Default data for the login handler.
+    @param eventhandler: Event handler to notify about new connections.
+    """
+
+    # These 4 may not be private as they are used by appserver to clone the
+    # connection manager.
+    self._location     = location
     self._loginHandler = loginHandler
     self._loginOptions = loginOptions
-    self._parser = RawConfigParser()
-    self._location = location
-    self._authenticatedUsers = {}
-    self._eventHandler=eventhandler
+    self._eventHandler = eventhandler
 
-    if len(location):
-      fileHandle = openResource(location)
+    # Primary connection names and their parameters
+    self.__primaries = {}
 
+    # Alias connection names and their parameters
+    self.__aliases = {}
+
+    # All connection names and their parameters
+    self.__definitions = {}
+
+    # Dictionary of authenticated users per connection name.
+    self.__authenticatedUsers = {}
+
+    # Dictionary of open connections (GConnection objects) per connection name.
+    self.__openConnections = {}
+
+    # Parse the connections.conf file
+    parser = RawConfigParser ()
+
+    if len (self._location):
+      fileHandle = openResource (self._location)
+
       try:
-        self._parser.readfp(fileHandle)
+        parser.readfp (fileHandle)
 
       except DuplicateSectionError:
         tmsg =  u_("The connections file has duplicate source definitions."
@@ -114,112 +151,123 @@
                    "\n\nFile: %s") % location
         raise InvalidFormatError, tmsg
 
-    self._openConnections = {}
-
-    self._primaries = {}
-    self._aliases = {}
-    self._definitions = {}
-
-
     # Read all the sections into a dict
     # and make a note of all alias names
-    for section in self._parser.sections():
-       self._primaries[section]={}
-       for att in self._parser.options(section):
+    for section in parser.sections ():
+       self.__primaries [section] = {}
+       for att in parser.options (section):
          if att == 'aliases':
-           for alias in ((self._parser.get(section,att)).lower ()).split ():
-             self._aliases[alias] = section
+           for alias in ((parser.get (section,att)).lower ()).split ():
+             self.__aliases [alias] = section
          else:
-           self._primaries[section][att] = self._parser.get(section, att)
+           self.__primaries [section] [att] = parser.get (section, att)
 
     # Fill in any aliases with their parameters
-    for alias in self._aliases.keys():
-      section = self._aliases[alias]
-      self._aliases[alias] = copy.copy(self._primaries[section])
-      self._aliases[alias]['_alias_of'] = section
+    for alias in self.__aliases.keys():
+      section = self.__aliases [alias]
+      self.__aliases [alias] = copy.copy (self.__primaries [section])
+      self.__aliases [alias] ['_alias_of'] = section
 
+    # Create the dictionary with both primaries and aliases
+    self.__definitions.update (self.__aliases)
+    self.__definitions.update (self.__primaries)
 
-    self._definitions.update(self._aliases)
-    self._definitions.update(self._primaries)
 
-
   # ---------------------------------------------------------------------------
   # Set the login handler for opening connections
   # ---------------------------------------------------------------------------
 
-  def setLoginHandler(self, loginHandler):
+  def setLoginHandler (self, loginHandler):
+    """
+    Set the login handler to use to ask the user for login data.
+    """
+
     self._loginHandler = loginHandler
-    try:
-      loginHandler.defaults.update(self._loginOptions)
-    except AttributeError:
-      print "WARNING: Login handler doesn't support 'default' login info."
 
 
   # ---------------------------------------------------------------------------
   # Check if a parameter is given for a connection
   # ---------------------------------------------------------------------------
 
-  def hasConnectionParameters(self, connection_name):
-    return self._definitions.has_key(connection_name)
+  def hasConnectionParameters (self, connection_name):
+    """
+    Check if the given connection name exists in the connections.conf file.
+    """
 
+    return self.__definitions.has_key (connection_name)
 
+
   # ---------------------------------------------------------------------------
   # Get a parameter for a connection
   # ---------------------------------------------------------------------------
 
-  def getConnectionParameter(self, connection_name, attribute, default=None):
+  def getConnectionParameter (self, connection_name, attribute, default = 
None):
+    """
+    Read a parameter from the connections.conf file.
+    """
+
     try:
-      definition = self._definitions[connection_name]
+      definition = self.__definitions [connection_name]
       try:
-        return definition[attribute]
+        return definition [attribute]
       except:
         return default
     except KeyError:
-      tmsg = u_("The connections file does not contain a definition "
-                "for \"%(connection)s\".\n\nFile: %(file)s") \
-             % {'connection': connection_name,
-                'file'      : self._location}
-      raise NotFoundError, tmsg
+      raise NotFoundError, connection_name, self._location
 
 
   # ---------------------------------------------------------------------------
-  # Returns an dictionary of dictionaries describing all connections:
-  #  {connection name: {att name: value}}
+  # Returns a list of connection names
   # ---------------------------------------------------------------------------
 
-  def getConnectionNames(self, includeAliases=True):
+  def getConnectionNames (self, includeAliases = True):
+    """
+    Return a list of all connections from the connections.conf file.
+
+    @param includeAliases: Whether or not to include connection aliases.
+    @return: List with all connection names.
+    """
+
     if includeAliases:
-      return self._definitions.keys()
+      return self.__definitions.keys ()
     else:
-      return self._primaries.keys()
+      return self.__primaries.keys ()
 
 
   # ---------------------------------------------------------------------------
-  # Returns an dictionary of dictionaries describing all connections:
-  #  {connection name: {att name: value}}
+  # Returns an dictionary of dictionaries describing all connections
   # ---------------------------------------------------------------------------
 
-  def getAllConnectionParameters(self, includeAliases=1):
+  def getAllConnectionParameters (self, includeAliases = 1):
+    """
+    Return a dictionary of all connections from the connections.conf file.
+
+    @param includeAliases: Whether or not to include connection aliases.
+    @return: Dictionary where the keys are connection names and the values are
+      dictionaries with all connection parameters.
+    """
+
     if includeAliases:
-      return copy.deepcopy(self._definitions)
+      return copy.deepcopy (self.__definitions)
     else:
-      return copy.deepcopy(self._primaries)
+      return copy.deepcopy (self.__primaries)
 
 
   # ---------------------------------------------------------------------------
-  # Returns a dictionary describing a connection:
-  #  {att name: value}
+  # Returns a dictionary describing a connection
   # ---------------------------------------------------------------------------
 
-  def getConnectionParameters(self, connection_name):
+  def getConnectionParameters (self, connection_name):
+    """
+    Return the parameter dictionary for a given connection.
+
+    @return: Dictionary with parameter name and parameter value.
+    """
+
     try:
-      return copy.deepcopy(self._definitions[connection_name])
+      return copy.deepcopy (self.__definitions [connection_name])
     except KeyError:
-      tmsg = u_("The connections file does not contain a definition "
-                "for \"%(connection)s\".\n\nFile: %(file)s") \
-             % {'connection': connection_name,
-                'file'      : self._location}
-      raise NotFoundError, tmsg
+      raise NotFoundError, connection_name, self._location
 
 
   # ---------------------------------------------------------------------------
@@ -229,18 +277,29 @@
   # ---------------------------------------------------------------------------
 
   def addConnectionSpecification (self, name, parameters):
-    self._definitions [name.lower ()] = copy.copy (parameters)
+    """
+    Add a session specific connection entry.
 
+    With this function, a temporary connection definition can be inserted
+    without having to change the connections.conf file.
 
+    @param name: Connection name.
+    @param parameters: Connection parameters as a dictionary.
+    """
+
+    self.__definitions [name.lower ()] = copy.copy (parameters)
+
+
   # ---------------------------------------------------------------------------
   # get a connection instance and optionally log into it
   # ---------------------------------------------------------------------------
 
   def getConnection (self, connection_name, login = False):
     """
-    This function returns an instance of the requested connection and
-    optionally logs into it. If there's an already opened connection for the
-    requested connectionname this instance will be returned.
+    Return an instance of the requested connection and optionally log into it.
+    
+    If there's an already opened connection for the requested connectionname
+    this instance will be returned.
 
     @param connection_name: name of the connection to be returned
     @param login: if TRUE, this function automatically tries to open the
@@ -248,10 +307,11 @@
     @return: connection instance
     @raise GConnection.NotFoundError: if connection_name does not exist
     """
+
     connection_name = connection_name.lower ()
 
-    if self._openConnections.has_key (connection_name):
-      conn = self._openConnections [connection_name]
+    if self.__openConnections.has_key (connection_name):
+      conn = self.__openConnections [connection_name]
     else:
 
       # Support for multiple open connections to the same database.
@@ -269,7 +329,7 @@
                               'Connection')
       conn = dbdriver.Connection (self, connection_name, parameters)
 
-      self._openConnections [connection_name] = conn
+      self.__openConnections [connection_name] = conn
 
     if login:
       self.loginToConnection (conn)
@@ -281,17 +341,31 @@
   # Has a connection been initialized/established?
   # ---------------------------------------------------------------------------
 
-  # TODO: this was likely broken
-  def isConnectionActive(self, connection):
-    return self._openConnections.has_key (connection.lower ())
+  def isConnectionActive (self, connection):
+    """
+    Return True if there is an open connection for the given connection name.
 
+    @param connection: Connection name.
+    @return: True if this connection is open, False otherwise.
+    """
 
+    return self.__openConnections.has_key (connection.lower ())
+
+
   # ---------------------------------------------------------------------------
   # login to a connection
   # ---------------------------------------------------------------------------
 
   def loginToConnection (self, connection):
+    """
+    Log into a connection.
 
+    This is called automatically at the end of L{getConnection} if the login
+    parameter is set to True.
+
+    @param connection: Connection name.
+    """
+
     connection_name = connection.name
     connection_base = connection_name.split (':') [0]
 
@@ -340,7 +414,11 @@
         loginData ['_password'] = loginData ['password']
         del loginData ['password']
 
-      # Load
+      # Override with data provided on command line so this has highest
+      # priority.
+      loginData.update (self._loginOptions)
+
+      # Load authenticator if needed
       if loginData.has_key ('custom_auth'):
         authenticator = dyn_import (loginData ['custom_auth']).Authenticator ()
         checkFields   = authenticator.getLoginFields ( \
@@ -426,10 +504,10 @@
 
       # Add to authenticated user list
       try:
-        self._authenticatedUsers [connection] = loginData ['_username']
+        self.__authenticatedUsers [connection] = loginData ['_username']
 
       except KeyError:
-        self._authenticatedUsers [connection] = None
+        self.__authenticatedUsers [connection] = None
 
 
       if self._eventHandler:
@@ -444,12 +522,16 @@
   # Get the user name that has logged into a connection
   # ---------------------------------------------------------------------------
 
-  def getAuthenticatedUser(self, connection=None):
+  def getAuthenticatedUser (self, connection = None):
+    """
+    Return the user name that has been used to log into the give connection.
+    """
+
     try:
-      if connection == None:
-        return self._authenticatedUsers[self._authenticatedUsers.keys()[0]]
+      if connection is None:
+        return self.__authenticatedUsers [self.__authenticatedUsers.keys () 
[0]]
       else:
-        return self._authenticatedUsers[connection]
+        return self.__authenticatedUsers [connection]
     except (KeyError, IndexError):
       return None
 
@@ -458,11 +540,12 @@
   # Committ all connections
   # ---------------------------------------------------------------------------
 
-  def commitAll(self):
+  def commitAll (self):
     """
-    This function commits all transactions
+    This function commits all transactions for all open connections.
     """
-    for connection in self._openConnections.values():
+
+    for connection in self.__openConnections.values():
       connection.commit()
 
 
@@ -472,9 +555,10 @@
 
   def rollbackAll(self):
     """
-    This function rolls back all transactions
+    This function rolls back all transactions for all open connections.
     """
-    for connection in self._openConnections.values():
+
+    for connection in self.__openConnections.values():
       connection.rollback()
 
 
@@ -486,11 +570,12 @@
     """
     This function closes all open connections.
     """
-    for connection in self._openConnections.values():
+
+    for connection in self.__openConnections.values():
       connection.close ()
 
-      if self._authenticatedUsers.has_key (connection):
-        del self._authenticatedUsers [connection]
+      if self.__authenticatedUsers.has_key (connection):
+        del self.__authenticatedUsers [connection]
 
-    for k in self._openConnections.keys ():
-      del self._openConnections [k]
+    for k in self.__openConnections.keys ():
+      del self.__openConnections [k]

Modified: trunk/gnue-common/src/datasources/GLoginHandler.py
===================================================================
--- trunk/gnue-common/src/datasources/GLoginHandler.py  2005-08-08 21:41:12 UTC 
(rev 7803)
+++ trunk/gnue-common/src/datasources/GLoginHandler.py  2005-08-09 17:02:34 UTC 
(rev 7804)
@@ -36,16 +36,12 @@
     errors.UserError.__init__ (self, msg)
 
 
-
 # =============================================================================
 # Base class for all login handler
 # =============================================================================
 
 class LoginHandler:
 
-  # The client app can set any default values for the needed parameters.
-  defaults = {}
-
   # ---------------------------------------------------------------------------
   # Get login information (depreciated)
   # ---------------------------------------------------------------------------

Modified: trunk/gnue-common/src/datasources/readgsd.py
===================================================================
--- trunk/gnue-common/src/datasources/readgsd.py        2005-08-08 21:41:12 UTC 
(rev 7803)
+++ trunk/gnue-common/src/datasources/readgsd.py        2005-08-09 17:02:34 UTC 
(rev 7804)
@@ -20,6 +20,9 @@
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
 # $Id$
+"""
+Program to import gsd files.
+"""
 
 import os
 import re
@@ -112,6 +115,9 @@
 # =============================================================================
 
 class gsdClient (GClientApp.GClientApp):
+  """
+  Client application for reading and importing gsd files.
+  """
 
   NAME    = "readgsd"
   COMMAND = "readgsd"





reply via email to

[Prev in Thread] Current Thread [Next in Thread]