source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/classfactory.py @ 4569

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/classfactory.py@4569
Revision 4569, 3.7 KB checked in by pjkersha, 12 years ago (diff)

Renamed classfactory and configfileparsers modules.

Line 
1"""
2Generic parsers to use when reading in configuration data
3- methods available to deal with both XML and INI (flat text key/val) formats
4"""
5__author__ = "C Byrom - Tessella"
6__date__ = "28/08/08"
7__copyright__ = "(C) 2008 STFC & NERC"
8__license__ = \
9"""This software may be distributed under the terms of the Q Public
10License, version 1.0 or later."""
11__contact__ = "Philip.Kershaw@stfc.ac.uk"
12__revision__ = '$Id$'
13
14import logging, os, sys
15log = logging.getLogger(__name__)
16
17class ClassFactoryError(Exception):
18    """Exception handling for NDG classfactory module."""
19    def __init__(self, msg):
20        log.error(msg)
21        Exception.__init__(self, msg)
22
23
24def instantiateClass(moduleName, className, moduleFilePath=None, 
25                     objectType=None, classProperties={}):
26    '''
27    Create and return an instance of the specified class
28    @param moduleName: Name of module containing the class
29    @type moduleName: str
30    @param className: Name of the class to instantiate
31    @type className: str
32    @keyword moduleFilePath: Path to the module - if unset, assume module on
33    system path already
34    @type moduleFilePath: str
35    @keyword classProperties: dict of properties to use when instantiating the
36    class
37    @type classProperties: dict
38    @keyword objectType: expected type for the object to instantiate - to
39    enforce use of specific interfaces
40    @type objectType: object
41    @return: object - instance of the class specified
42    '''
43
44    log.debug("Instantiating class, %s" % className)
45   
46    # ensure that classproperties is a dict - NB, it may be passed in as a null
47    # value which can override the default val
48    if not classProperties:
49        classProperties = {}
50
51    # variable to store original state of the system path
52    sysPathBak = None
53    try:
54        try:
55            # Module file path may be None if the new module to be loaded
56            # can be found in the existing system path           
57            if moduleFilePath:
58                if not os.path.exists(moduleFilePath):
59                    raise IOError("Module file path '%s' doesn't exist" % \
60                                  moduleFilePath)
61                         
62                # Temporarily extend system path ready for import
63                sysPathBak = sys.path
64                         
65                sys.path.append(moduleFilePath)
66
67#            from paste.util.import_string import eval_import
68#            mod = eval_import(moduleName)
69           
70            # Import module name specified in properties file
71            importModule=__import__(moduleName,globals(),locals(),[className])
72
73            #importClass = getattr(importModule, className)
74            importClass = eval('importModule.'+className)
75        finally:
76            # revert back to original sys path, if necessary
77            # NB, python requires the use of a try/finally OR a try/except
78            # block - not both combined
79            if sysPathBak:
80                sys.path = sysPathBak
81                           
82    except Exception, e:
83        raise ClassFactoryError('Error importing %s module: %s'%(moduleName,e))
84
85    # Check class inherits from AAproxy abstract base class
86    if objectType and not issubclass(importClass, objectType):
87        raise ClassFactoryError("Specified class %s must be derived from %s" %
88                                (className, objectType))
89
90    # Instantiate class
91    try:
92        object = importClass(**classProperties)
93        log.info('Instantiated "%s" class from module, "%s"' % (className,
94                                                                moduleName))
95        return object
96
97    except Exception, e:
98        log.error("Error instantiating class, %s: %s"%(importClass.__name__,e))
99        raise
100           
101                 
Note: See TracBrowser for help on using the repository browser.