def __write(self, context, category, message, strat_list=[]): """ Base method for writing a log entry to all log strategies. """ # log only specified categories if ( category not in self.__category_list and\ ALL not in self.__category_list ) or\ category in self.__category_exclude_list: return # load the file self.__load_log() # if we could not load the file, exit silently if self.__log_file == None: sys.stderr.write( "\nERROR: Null log file descriptor; no log entry written.") return # log details if user desires if self.__log_details == 1: message = string.strip(message) details = "(logged in %s on line %s)" % (getSourceFileName(2), getLineNumber(2)) tb = "" if traceBack() != "(no exceptions)": tb = "(traceback)\n%s" % (traceBack()) message = "%s\n%s\n%s" % (details, message, tb) try: # first log to the log file self.__file_lock('lock') self.__write_to_file(context, category, message) self.__file_lock('un-lock') # write all available strategies # NOTE: it is expected that additional strategies are # are thread safe. for strat in self.__strategy_dict.keys(): if strat in strat_list or 'all' in strat_list: self.__strategy_dict[strat].write_entry(context=context, category=category, message=message) else: # don't do anything pass except: sys.stderr.write( "\nERROR: Could not write to one or more strategies.\n") sys.stderr.write("\nMESSAGE:\n%s\n" % (message)) sys.stderr.write("\nTRACE BACK:\n%s\n" % (traceBack())) self.__file_lock('un-lock') pass
def __write( self, context, category, message, strat_list=[] ): """ Base method for writing a log entry to all log strategies. """ # log only specified categories if ( category not in self.__category_list and\ ALL not in self.__category_list ) or\ category in self.__category_exclude_list: return # load the file self.__load_log() # if we could not load the file, exit silently if self.__log_file == None: sys.stderr.write( "\nERROR: Null log file descriptor; no log entry written." ) return # log details if user desires if self.__log_details == 1: message = string.strip( message ) details = "(logged in %s on line %s)"%( getSourceFileName(2), getLineNumber(2) ) tb = "" if traceBack() != "(no exceptions)": tb = "(traceback)\n%s"%( traceBack() ) message = "%s\n%s\n%s"%( details, message, tb ) try: # first log to the log file self.__file_lock( 'lock' ) self.__write_to_file( context, category, message ) self.__file_lock( 'un-lock' ) # write all available strategies # NOTE: it is expected that additional strategies are # are thread safe. for strat in self.__strategy_dict.keys(): if strat in strat_list or 'all' in strat_list: self.__strategy_dict[ strat ].write_entry( context=context, category=category, message=message ) else: # don't do anything pass except: sys.stderr.write( "\nERROR: Could not write to one or more strategies.\n" ) sys.stderr.write( "\nMESSAGE:\n%s\n"%( message ) ) sys.stderr.write( "\nTRACE BACK:\n%s\n"%( traceBack() ) ) self.__file_lock( 'un-lock' ) pass
def getDataAccess(self, config_dict): strategy = config_dict.get('strategy', None) if strategy == None: raise DBInitError("No database 'strategy' specified.") elif strategy not in STRATEGY_DICT.keys(): raise DBInitError("Database strategy '%s' not supported." % (strategy)) module_name = "wpl.dbnew.%s" % (STRATEGY_DICT[strategy]) try: module = __import__(module_name) components = string.split(module_name, '.') for comp in components[1:]: module = getattr(module, comp) exec("db_strategy = module.%s( config_dict )" % (STRATEGY_DICT[strategy])) return db_strategy except: raise DBInitError( "Could not instantiate strategy '%s' from module '%s'.\nDetails: %s" % (strategy, module_name, traceBack()))
def __load_log( self ): """ Loads a specified log file, roteates logs, and sets the today link to the currently loaded log. """ # load the log file if the log file name is none # or if the file name has changed if self.__log_file == None or self.__generate_file_name() == 1: try: self.__log_file = open( self.__log_file_name, 'a' ) link_name = string.join( [self.__base_name , TODAY_S_LINK], '.' ) # if link exists remove it if os.path.islink( os.path.join( self.__path, link_name ) ): # DEBUG #print "removing link." os.unlink( os.path.join( self.__path, link_name ) ) # set a softlink 'today' to point to the current log os.symlink( self.__log_file_name , os.path.join( self.__path, link_name ) ) except: sys.stderr.write( "\nERROR: LogWriter could not create log file name '%s'."%( self.__log_file_name ) ) sys.stderr.write( "\nTRACE BACK:\n%s."%( traceBack() ) ) self.__log_file = None else: pass
def __init__(self, db_config_dict ): #print '%s %s %s' % (confFile, confSectionName, strategy) self.db_config_dict = db_config_dict strategy = string.lower( db_config_dict.get( 'strategy', None ) ) if strategy == None: raise DBInitError("No valid connection strategy specified. Make sure to specify a 'strategy' key.") try: strategy_name = "%sStrategy"%( strategy ) strategy_module_name = "wpl.db.%s"%( strategy_name ) DBModule = __import__( strategy_module_name ) components = string.split( strategy_module_name, '.') for comp in components[1:]: DBModule = getattr(DBModule, comp) #sys.stderr.write( "imported DBModule %s"%( dir(DBModule) ) ) # create a new instance exec_args = " self.db_config_dict " exec_string = "self.Strategy = DBModule.%s( %s )"%( strategy_name, exec_args ) exec( exec_string ) except: raise DBInitError( "FATAL ERROR: Could not import and instantiate appropriate DB strategy.\ \nDetails: %s"%( traceBack() ) )
def __init__(self, confFile="sql.conf", confSectionName="Database", strategy="MySQL", **props): #print '%s %s %s' % (confFile, confSectionName, strategy) try: config=ConfigParser.ConfigParser() config.read(confFile) try: if strategy == None: strategy = config.get(confSectionName,'strategy') except: pass except: raise DBInitError('Configuration file %s is missing.' % confFile) if strategy == None: raise DBInitError('No valid connection strategy specified.') try: # OLD stmt from hw -> DBModule = __import__('DBStrategy' + strategy) DBModule = __import__('wpl.db.DBStrategy' + strategy ) components = string.split('wpl.db.DBStrategy' + strategy, '.') for comp in components[1:]: DBModule = getattr(DBModule, comp) #sys.stderr.write( "imported DBModule %s"%( dir(DBModule) ) ) self.Strategy = apply(DBModule.DBStrategy, [confFile, confSectionName], props) except: raise DBInitError(('Illegal DB Strategy %s; Stack: ' % strategy) + traceBack())
def __load_log(self): """ Loads a specified log file, roteates logs, and sets the today link to the currently loaded log. """ # load the log file if the log file name is none # or if the file name has changed if self.__log_file == None or self.__generate_file_name() == 1: try: self.__log_file = open(self.__log_file_name, 'a') link_name = string.join([self.__base_name, TODAY_S_LINK], '.') # if link exists remove it if os.path.islink(os.path.join(self.__path, link_name)): # DEBUG #print "removing link." os.unlink(os.path.join(self.__path, link_name)) # set a softlink 'today' to point to the current log os.symlink(self.__log_file_name, os.path.join(self.__path, link_name)) except: sys.stderr.write( "\nERROR: LogWriter could not create log file name '%s'." % (self.__log_file_name)) sys.stderr.write("\nTRACE BACK:\n%s." % (traceBack())) self.__log_file = None else: pass
def execute(self, query): try: cursor = self.__db.query(query) except: raise DBCommError("stacktrace:\n%s" % traceBack()) cursor = DataAccess.DataAccessCursor(cursor, cursor.dictresult) return cursor
def process( self ): """ Main method called by WebForm auto dispatcher to begin processing. Handles locating and loading a project based on the URL call. """ if self.driver_conf == None: self.__panic( "Missing DriverConf.py" , """Could not find module DriverConf.py in the slither directory. Please make sure that this file exists and has the appropriate permissions. """ ) # attempt to get the project binding dict if not hasattr( self.driver_conf, "projects" ): self.__panic( "Missing 'projects' dictionary.", """Could not find the 'projects' directory in DriverConf.py. Please make sure that the dictionary exists and properly defined. """ ) self.__project_dict = getattr( self.driver_conf, "projects" ) self.logger.writeDebug( "Loaded base projects dictionary.\nproject_dict = %s"%( self.__project_dict ) ) # parse the URL url_profile = self.__parse_url( os.environ.get( 'REQUEST_URI', '' ) ) # attempt to load the project ( project_profile, load_msg, tb ) = self.__load_project( url_profile ) if project_profile: try: self.logger.writeDebug( "Running project..." ) # dispatch the project output = project_profile['project'].run() change_cwd( self.__driver_path ) self.logger.writeDebug( "Printing result" ) #self.logger.writeEntry( "OUTPUT: %s"%(output[:500]) ) # output the results to the browser #sys.stdout.write( output ) sys.stdout.write( output ) except: # an error occured during dispatching sys.stdout = project_profile['project'].stdout_save error_msg = "Project '%s' experienced errors during execution.\n" % ( project_profile['project_name'] ) self.logger.writeError( error_msg ) change_cwd( self.__driver_path ) self.__panic( "Fatal project execution error.", error_msg, traceBack() ) else: sys.exit( 0 ) else: #error_msg = "One more problems encountered when loading the requested project.\n%s"%( load_msg ) self.logger.writeError( load_msg ) self.__panic( "Could not load project.", load_msg, tb )
def __init__(self, confFile="sql.conf", confSectionName="Database", **props): try: config=ConfigParser.ConfigParser() config.read(confFile) self.dbProp = config.get(confSectionName,'db') self.hostProp = config.get(confSectionName,'host') self.userProp = config.get(confSectionName,'user') self.passwordProp = config.get(confSectionName,'password') self.db = _pg.connect(dbname=self.dbProp,\ host=self.hostProp,\ user=self.userProp,\ passwd=self.passwordProp) except: raise DBInitError("StackTrace -> " + traceBack())
def getMySQLdb(module): try: MySQLdb = __import__(module) components = string.split(module, '.') for comp in components[1:]: MySQLdb = getattr(MySQLdb, comp) except ImportError: raise ImportError('Cannot import %s.\nDetails: %s'%( str(module), traceBack()) ) if not hasattr(MySQLdb, 'DictCursor'): raise ImportError('Module %s does support dictionary cursors.' % module) return MySQLdb
def execute(self, query): # erase our warning if there was any self.warning = {} #tempcursor = self.__db.cursor() #cursor = DataAccess.DataAccessCursor(tempcursor, \ # tempcursor.fetchallDict) cursor = self.getNewCursor() try: cursor.execute(query) #print "Peformed query." except MySQLdb.Warning, details: self.warning["details"] = details self.warning["traceback"] = traceBack()
def __init__(self, confFile="sql.conf", confSectionName="Database", **props): #print 'conf %s section %s extra %s' % (confFile, confSectionName, props) try: config=ConfigParser.ConfigParser() config.read(confFile) self.dbProp = config.get(confSectionName,'db') self.hostProp = config.get(confSectionName,'host') self.userProp = config.get(confSectionName,'user') self.passwordProp = config.get(confSectionName,'password') # load the port try: self.portProp = config.getint(confSectionName,'port') except: self.portProp = None # The 'mysqldb' property can be specified in the config file # instead of as a keyword argument; however, if it is present # as a keyword argument, the option in the configuration file # is ignored. self.mysqldbProp = DEFAULT_MYSQLDB try: if not props.has_key('MySQLdb'): self.mysqldbProp = config.get(confSectionName, 'mysqldb') except: pass MySQLdbModuleName = props.get('MySQLdb', self.mysqldbProp) self.MySQLdb = MySQLdbKludge.getMySQLdb(MySQLdbModuleName) if self.portProp != None: db = self.MySQLdb.connect(db=self.dbProp,\ host=self.hostProp,\ port=self.portProp, \ user=self.userProp,\ passwd=self.passwordProp,\ cursorclass=self.MySQLdb.DictCursor) else: db = self.MySQLdb.connect(db=self.dbProp,\ host=self.hostProp,\ user=self.userProp,\ passwd=self.passwordProp,\ cursorclass=self.MySQLdb.DictCursor ) self.cursor = db.cursor() except: raise DBInitError( "StackTrace -> " + traceBack() )
def __init__(self, confFile="sql.conf", confSectionName="Database", **props): try: config = ConfigParser.ConfigParser() config.read(confFile) self.dbProp = config.get(confSectionName, 'db') self.hostProp = config.get(confSectionName, 'host') self.userProp = config.get(confSectionName, 'user') self.passwordProp = config.get(confSectionName, 'password') self.db = _pg.connect(dbname=self.dbProp,\ host=self.hostProp,\ user=self.userProp,\ passwd=self.passwordProp) except: raise DBInitError("StackTrace -> " + traceBack())
def __parse_form(self, form): """ Parses the cgi.field storag object into a directory name space.""" # create the form and file directory #self.data_dir.create( "/form" ) #self.data_dir.cd( "/form" ) # go through each field storage data item and # add the values to the form dir for var in form.keys(): try: if type(form[var]) == type([]): # this is a list, first parse it new_list = [] for item in form[var]: # each is a field storage object if item.filename == None: new_list.append(item.value) else: new_list.append((item.filename, item.file)) # add the new list to /form #self.data_dir[ var ] = new_list self.form[var] = new_list elif form[var].filename == None: # this is not a file, just add it #self.data_dir[ var ] = form[ var ].value self.form[var] = form[var].value else: # this is a file #self.data_dir[ var ] = ( form[ var ].filename, form[ var ].file ) self.form[var] = (form[var].filename, form[var].file) except: raise Exception( "ERROR: While parsing cgi FieldStorage object. Details: %s" % (traceBack()))
def __init__(self, confFile="sql.conf", confSectionName="Database", strategy="MySQL", **props): #print '%s %s %s' % (confFile, confSectionName, strategy) try: config = ConfigParser.ConfigParser() config.read(confFile) try: if strategy == None: strategy = config.get(confSectionName, 'strategy') except: pass except: raise DBInitError('Configuration file %s is missing.' % confFile) if strategy == None: raise DBInitError('No valid connection strategy specified.') try: # OLD stmt from hw -> DBModule = __import__('DBStrategy' + strategy) DBModule = __import__('wpl.db.DBStrategy' + strategy) components = string.split('wpl.db.DBStrategy' + strategy, '.') for comp in components[1:]: DBModule = getattr(DBModule, comp) #sys.stderr.write( "imported DBModule %s"%( dir(DBModule) ) ) self.Strategy = apply(DBModule.DBStrategy, [confFile, confSectionName], props) except: raise DBInitError(('Illegal DB Strategy %s; Stack: ' % strategy) + traceBack())
# erase our warning if there was any self.warning = {} #tempcursor = self.__db.cursor() #cursor = DataAccess.DataAccessCursor(tempcursor, \ # tempcursor.fetchallDict) cursor = self.getNewCursor() try: cursor.execute(query) #print "Peformed query." except MySQLdb.Warning, details: self.warning["details"] = details self.warning["traceback"] = traceBack() except: raise DBCommError("stacktrace:\n%s" % traceBack()) self.__cursor = cursor return cursor def getNewCursor(self): tempcursor = self.__db.cursor() return DataAccess.DataAccessCursor( tempcursor, tempcursor.fetchallDict ) def getRecords(self): return self.__cursor.getRecords()
def execute(self, query): try: self.result = self.db.query(query) except: raise DBCommError("StackTrace -> " + traceBack())
def run( self ): """ Main method called to dispatch stages and handle stage exceptions. """ # capture all data written to the standard output stream # so that it can be safely emitted #stdout_capture = StringIO.StringIO() stdout_capture = stdout_to_log( self.logger ) self.stdout_save = sys.stdout sys.stdout = stdout_capture # load the session self.logger.writeEntry( "Loading session...", SYSTEM_LOG_DEBUG ) self.user_profile = self.session( 'load' ) # bind the user profile to Request self.Request.session = self.user_profile self.state_exception = ( None, None ) self.trace_back = "" # load exception and plugin tables try: self.logger.writeEntry( "Loading exception and plugin tables...", SYSTEM_LOG_DEBUG ) self.load_exceptions() self.load_plugins() except: self.logger.writeEntry( "Error while loading plugins and/or exceptions.", SYSTEM_LOG_ERROR ) self.logger.writeEntry( "Attempting to continue executing the request.\nDetails: %s"%( traceBack() ), SYSTEM_LOG_ERROR ) self.trace_back = traceBack() ######################### # begin execution of call #error_flag = 0 if self.trace_back == "": try: self.logger.writeEntry( "Calling preprocess...", SYSTEM_LOG_DEBUG ) self.preprocess() except: self.logger.writeEntry( "Error occured executing project's preprocess method.", SYSTEM_LOG_ERROR ) self.logger.writeEntry( "No states will be loaded.\nDetails: %s"%( traceBack() ), SYSTEM_LOG_ERROR ) self.trace_back = traceBack() # run loop paramters loop_control = 'run' out = '' first_state_profile = self.parse_state_path( self.project_profile[ 'project_state_path' ] ) call_path = first_state_profile[ 'call_path' ] load_path = self.project_profile[ 'project_state_path' ] last_call_path = '' state_profile = None load_msg = '' loop_count = -1 # must start at -1 because it is called at teh top of the loop while( loop_control=='run' and self.trace_back == "" ): loop_count = loop_count + 1 # check loop count to make sure we are not in a cycle if loop_count > self.__max_transitions: self.logger.writeEntry( "Loop count exceeded maximum count.", SYSTEM_LOG_ERROR ) self.logger.writeEntry( "You might thave a cycle in your code. Calling project's render().", SYSTEM_LOG_ERROR ) out = self.render() break; # set params. for loading the state if last_call_path != call_path: self.logger.writeEntry( "Loading state: call_path '%s', last_call_path '%s'"%( call_path, last_call_path ), SYSTEM_LOG_DEBUG ) state_profile = self.load_state_module( load_path ) if state_profile == None: self.logger.writeEntry( "Could not load state; calling default project render().", SYSTEM_LOG_DEBUG ) out = self.render() break; elif state_profile[ 'method' ][0] == "_": # attempted to load a protectedor private method # reject and call default render self.logger.writeEntry( "Attempted to call protected/private method %s; \ default project render() called."%(state_profile[ 'method' ]), SYSTEM_LOG_WARNING ) out = self.render() break; try: # change cwd to the state object directory change_cwd( state_profile['full_path'] ) # capture the state profile prior to run # used later to detect state changes last_call_path = state_profile[ 'call_path' ] self.logger.writeEntry( "Setting last_call_path to %s."%( last_call_path ), SYSTEM_LOG_DEBUG ) self.logger.writeEntry( "Calling method %s()..."%(state_profile[ 'method' ]), SYSTEM_LOG_DEBUG ) # get a handle to the funtion (exceptions are raised if the function does not exist) func = getattr( state_profile[ 'state' ], state_profile[ 'method' ] ) # call the function out = apply( func, [], {} ) # cahnge cwd to back to project change_cwd( self.project_profile['webroot'] ) # no exeptions raised; clear last exception self.state_exception = ( None, None ) except StageProcessException, details: self.logger.writeEntry( "State %s raised StageProcessException."%( state_profile['state_name'] ), SYSTEM_LOG_DEBUG ) out = details break; except:
return self.__db def execute(self, query): # erase our warning if there was any self.warning = {} #tempcursor = self.__db.cursor() #cursor = DataAccess.DataAccessCursor(tempcursor, \ # tempcursor.fetchallDict) cursor = self.getNewCursor() try: cursor.execute(query) #print "Peformed query." except MySQLdb.Warning, details: self.warning["details"] = details self.warning["traceback"] = traceBack() except: raise DBCommError("stacktrace:\n%s" % traceBack()) self.__cursor = cursor return cursor def getNewCursor(self): tempcursor = self.__db.cursor() return DataAccess.DataAccessCursor(tempcursor, tempcursor.fetchallDict) def getRecords(self): return self.__cursor.getRecords()
# cahnge cwd to back to project change_cwd( self.project_profile['webroot'] ) # no exeptions raised; clear last exception self.state_exception = ( None, None ) except StageProcessException, details: self.logger.writeEntry( "State %s raised StageProcessException."%( state_profile['state_name'] ), SYSTEM_LOG_DEBUG ) out = details break; except: self.logger.writeEntry( "Exception caught while executing state method.\nDetails: %s"%( traceBack() ),SYSTEM_LOG_ERROR ) self.logger.writeEntry( "Attempting to look up exception handler...", SYSTEM_LOG_DEBUG ) # attempt to locate a handler for the exception handler = self.exception_table.getHandler( sys.exc_info()[0] ) # capture exception if self.state_exception[0] == sys.exc_info()[0]: self.logger.writeEntry( "Exception '%s' called more than once consecutively."%( self.state_exception[0] ), SYSTEM_LOG_DEBUG ) out = self.render() break; else: self.state_exception = ( sys.exc_info()[0], sys.exc_info()[1] )
except ImportError, details: error_msg = "Could not import project module '%s' for project name '%s'.\n \ Check that the module exists at the specified file path.\n \ %s" % (project_profile['project_module'], project_name, details) tb = "" except AttributeError, details: error_msg = "Could not instantiate class '%s' for project \n \ name '%s'. Make sure the class name is correct in module '%s'." % ( project_profile['project_class'], project_profile['project_name'], project_profile['project_module'], ) tb = traceBack() except: error_msg = "Unexpected error while loading project '%s'." % ( project_name) tb = traceBack() # post exception processing self.logger.writeError(error_msg + "Traceback: " + tb) change_cwd(self.__driver_path) return (None, error_msg, tb) def __parse_url(self, url): """ Internal method used to parse the calling URL into
def execute(self,query): try: self.result = self.db.query(query) except: raise DBCommError("StackTrace -> " + traceBack())
def process(self): """ Main method called by WebForm auto dispatcher to begin processing. Handles locating and loading a project based on the URL call. """ if self.driver_conf == None: self.__panic( "Missing DriverConf.py", """Could not find module DriverConf.py in the slither directory. Please make sure that this file exists and has the appropriate permissions. """ ) # attempt to get the project binding dict if not hasattr(self.driver_conf, "projects"): self.__panic( "Missing 'projects' dictionary.", """Could not find the 'projects' directory in DriverConf.py. Please make sure that the dictionary exists and properly defined. """ ) self.__project_dict = getattr(self.driver_conf, "projects") self.logger.writeDebug( "Loaded base projects dictionary.\nproject_dict = %s" % (self.__project_dict)) # parse the URL url_profile = self.__parse_url(os.environ.get('REQUEST_URI', '')) # attempt to load the project (project_profile, load_msg, tb) = self.__load_project(url_profile) if project_profile: try: self.logger.writeDebug("Running project...") # dispatch the project output = project_profile['project'].run() change_cwd(self.__driver_path) self.logger.writeDebug("Printing result") #self.logger.writeEntry( "OUTPUT: %s"%(output[:500]) ) # output the results to the browser #sys.stdout.write( output ) sys.stdout.write(output) except: # an error occured during dispatching sys.stdout = project_profile['project'].stdout_save error_msg = "Project '%s' experienced errors during execution.\n" % ( project_profile['project_name']) self.logger.writeError(error_msg) change_cwd(self.__driver_path) self.__panic("Fatal project execution error.", error_msg, traceBack()) else: sys.exit(0) else: #error_msg = "One more problems encountered when loading the requested project.\n%s"%( load_msg ) self.logger.writeError(load_msg) self.__panic("Could not load project.", load_msg, tb)
def __parse_form( self, form ): """ Parses the cgi.field storag object into a directory name space.""" # create the form and file directory #self.data_dir.create( "/form" ) #self.data_dir.cd( "/form" ) # go through each field storage data item and # add the values to the form dir for var in form.keys(): try: if type( form[ var ] ) == type( [] ): # this is a list, first parse it new_list = [] for item in form[ var ]: # each is a field storage object if item.filename == None: new_list.append( item.value ) else: new_list.append( ( item.filename, item.file ) ) # add the new list to /form #self.data_dir[ var ] = new_list self.form[ var ] = new_list elif form[ var ].filename == None: # this is not a file, just add it #self.data_dir[ var ] = form[ var ].value self.form[ var ] = form[ var ].value else: # this is a file #self.data_dir[ var ] = ( form[ var ].filename, form[ var ].file ) self.form[ var ] = ( form[ var ].filename, form[ var ].file ) except: raise Exception( "ERROR: While parsing cgi FieldStorage object. Details: %s"%( traceBack() ) )
def execute(self,query): try: self.cursor.execute(query) except self.MySQLdb.Warning, details: raise DBWarning( "Details -> %s \n StackTrace -> %s" \ % (details, traceBack()))
cursorclass=self.MySQLdb.DictCursor ) self.cursor = db.cursor() except: raise DBInitError( "StackTrace -> " + traceBack() ) def getDb(self): return self.cursor # execute() must be Strategy-specific, since specific provider exceptions # are being thrown. def execute(self,query): try: self.cursor.execute(query) except self.MySQLdb.Warning, details: raise DBWarning( "Details -> %s \n StackTrace -> %s" \ % (details, traceBack())) except: raise DBCommError( "StackTrace -> " + traceBack() ) def getDictResult(self): return self.cursor.fetchallDict() def __str__(self): passwordEcho = '*' * len(self.passwordProp) return "MySQL Strategy -> db=%s host=%s user=%s password=%s" \ % (self.dbProp,self.hostProp,self.userProp,passwordEcho) __repr__ = __str__
def __cookie_strategy( self, operation, user_profile=None ): """ Internal method that implements session management with cookies. It will use an ID stored in as a cookie to locate a UserProfile object. Oherwise, it will create a new UserProfile object and store the assigned unique ID as a cookie. """ # check directory (chdir_result, chdir_msg) = change_cwd( self.__user_profile_dir, check_only=1 ) if not chdir_result: self.logger.writeEntry( "User profile directory '%s' is not \ valid or accessible.\n%s"%( self.__user_profile_dir, chdir_msg ), SYSTEM_LOG_ERROR ) return UserProfile() self.logger.writeEntry("__cookie_strategy: cwd = %s"%( os.getcwd() ), SYSTEM_LOG_DEBUG ) cookie = self.Request.get_cookie( self.__user_profile_cookie_name ) if operation == 'load' and cookie != None: self.logger.writeEntry( "__cookie_strategy: cookie : %s"%( cookie ), SYSTEM_LOG_DEBUG ) self.logger.writeEntry( "__cookie_strategy: cookie value : %s"%( cookie.value ), SYSTEM_LOG_DEBUG ) up_file_name = os.path.join( self.__user_profile_dir, cookie.value ) try: user_profile_file = open( up_file_name, 'r' ) user_profile = cPickle.load( user_profile_file ) user_profile_file.close() self.logger.writeEntry( "__cookie_strategy: Successfully loaded user profile for session %s."%(cookie.value), SYSTEM_LOG_DEBUG ) return user_profile except: self.logger.writeEntry( "__cookie_strategy: Exceptions raised while loading user profile file '%s'. Details: %s"%(up_file_name, traceBack() ), SYSTEM_LOG_WARNING ) self.logger.writeEntry( "__cookie_strategy: Creating and returning a fresh UserProfile." ) return UserProfile() elif operation == 'load' and cookie == None: self.logger.writeEntry( "__cookie_strategy: First time that user has accessd project. Creating new UserProfile.", SYSTEM_LOG_DEBUG ) return UserProfile() elif operation == 'save' and isinstance( user_profile, UserProfile ) == 1: up_file_name = os.path.join( self.__user_profile_dir, 'UserProfile.'+ user_profile.getId() ) try: #save the file user_profile_file = open( up_file_name, 'w' ) cPickle.dump( user_profile , user_profile_file ) user_profile_file.close() #cookie = self.get_new_cookie() #cookie[ self.__user_profile_cookie_name ] = 'UserProfile.'+ user_profile.getId() #cookie[ self.__user_profile_cookie_name ]['path'] = self.__session_access_path #cookie[ self.__user_profile_cookie_name ]['domain'] = self.__session_access_domain #cookie[ self.__user_profile_cookie_name ]['expires'] = self.__session_expiration self.Response.set_cookie( self.__user_profile_cookie_name, 'UserProfile.'+ user_profile.getId(), self.__session_access_domain, self.__session_access_path, self.__session_expiration ) self.logger.writeEntry( "__cookie_strategy: User profile cookie set with name: UserProfile.%s"%( user_profile.getId() ), SYSTEM_LOG_DEBUG ) except: self.logger.writeEntry( "__vookie_strategy: Error occured while saving user profile file '%s'.\nDetails: %s"%( up_file_name, traceBack() ), SYSTEM_LOG_DEBUG ) else: self.logger.writeEntry( "__cookie_strategy: Did not know how to handle operation '%s'. Nothing done."%( operation ), SYSTEM_LOG_WARNING ) self.logger.writeEntry( "__cookie_strategy: user_profile = %s"%( user_profile ), SYSTEM_LOG_DEBUG ) pass
tb = "" except ImportError, details : error_msg = "Could not import project module '%s' for project name '%s'.\n \ Check that the module exists at the specified file path.\n \ %s"%( project_profile[ 'project_module' ], project_name, details ) tb = "" except AttributeError, details : error_msg = "Could not instantiate class '%s' for project \n \ name '%s'. Make sure the class name is correct in module '%s'."%( project_profile['project_class'], project_profile['project_name'], project_profile['project_module'], ) tb = traceBack() except: error_msg = "Unexpected error while loading project '%s'."%( project_name ) tb = traceBack() # post exception processing self.logger.writeError( error_msg + "Traceback: " + tb ) change_cwd( self.__driver_path ) return ( None, error_msg, tb )