[Modeling-cvs] ProjectModeling/Modeling Model.py,1.4.2.1,1.4.2.2
Status: Abandoned
Brought to you by:
sbigaret
|
From: <sbi...@us...> - 2003-06-17 16:55:57
|
Update of /cvsroot/modeling/ProjectModeling/Modeling
In directory sc8-pr-cvs1:/tmp/cvs-serv4177
Modified Files:
Tag: brch-0_9pre7-1-PyModel
Model.py
Log Message:
Added updateModelWithCFG(), loadModel(), searchModel()
Index: Model.py
===================================================================
RCS file: /cvsroot/modeling/ProjectModeling/Modeling/Model.py,v
retrieving revision 1.4.2.1
retrieving revision 1.4.2.2
diff -C2 -d -r1.4.2.1 -r1.4.2.2
*** Model.py 15 May 2003 17:44:20 -0000 1.4.2.1
--- Model.py 17 Jun 2003 16:55:54 -0000 1.4.2.2
***************
*** 49,52 ****
--- 49,236 ----
from Persistent import Persistent
+ def updateModelWithCFG(model, cfg_path=None):
+ """
+ Updates the model's connection dictionary and adaptorName with the values
+ in file 'cfg_path'. If cfg_path is omitted or None, the value stored
+ in the environment variable MDL_DB_CONNECTIONS_CFG is used instead.
+
+ A sample configuration file is like::
+
+ [DEFAULT]
+ host: localhost
+
+ [ModelName_1]
+ user: user_1
+ password: pwd_1
+
+ [ModelName_2]
+ adaptor: MySQL
+ user: user_2
+ password: pwd_2
+
+ The special field 'adaptor', if present, changes the adaptorName of the
+ model.
+
+ Raises IOError if file 'cfg_path' cannot be found.
+
+ See also: ModelSet.addModel()
+
+ Parameters:
+
+ model -- the model whose conn.dict. should be updated
+
+ cfg_path -- the full path to the configuration file, or if omitted or
+ None, defaults to the value stored in the env. variable
+ MDL_DB_CONNECTIONS_CFG
+
+ """
+ import os
+ if cfg_path is None:
+ cfg_path=os.environ.get('MDL_DB_CONNECTIONS_CFG')
+
+ from ConfigParser import ConfigParser
+ defaults=model.connectionDictionary()
+ cp=ConfigParser()
+ try:
+ cp.readfp(open(cfg_path))
+ except IOError:
+ import traceback, cStringIO, sys
+ exc_raised=sys.exc_info()[:2]
+ err_msg="Unable to open file '%s' (passed in parameter 'cfg_path' or taken from env. variable MDL_DB_CONNECTIONS_CFG"%cfg_path
+ exc=cStringIO.StringIO()
+ traceback.print_exception(exc_raised[0], exc_raised[1], None, file=exc)
+ err_msg+="\nOriginal exception was: %s"%exc.getvalue()
+ raise IOError, err_msg
+
+ try: options=cp.options(model.name())
+ except: return
+ try: options.remove('adaptor')
+ except ValueError: pass
+ for key in options:
+ defaults[key]=cp.get(model.name(), key)
+ model.setConnectionDictionary(defaults)
+ try:
+ model.setAdaptorName(cp.get(model.name(), 'adaptor'))
+ except:
+ pass
+
+ def loadModel(path):
+ """
+ Load a model stored in the file 'path'. The lookup procedure is:
+
+ - if path ends with '.py', we assume it is a python module. This module is
+ imported and the following attributes are searched within it, in that
+ order:
+
+ 1. 'model' (either an attribute or a function): if found, we assume
+ this is an instance of Modeling.Model.Model and we return the value
+
+ 2. 'pymodel' (id.): if found, we assume this is an instance of
+ Modeling.PyModel.Model and we return its 'component' attribute
+
+ 3. 'model_src' (id.): if found, we assume this is a string and return
+ the model build from it with ModelSet.addModelFromXML()
+
+ - if path ends with '.xml', we assume this is a xml-file and we return the
+ model build with ModelSet.addModelFromXML()
+
+ Returns: the loaded Modeling.Model.Model instance
+
+ Raises IOError if file 'path' cannot be found
+
+ Parameter:
+
+ path -- the path of the file where the model is stored
+
+ """
+ if path[-3:]=='.py':
+ import os,imp
+ dir,filename=os.path.dirname(path),os.path.basename(path)
+ modulename=filename[:-3]
+ file=None
+ try:
+ try:
+ file,pathname,description=imp.find_module(modulename, [dir])
+ module=imp.load_module(modulename,file,pathname,description)
+
+ if hasattr(module, 'model'):
+ model=module.model
+ if callable(model):
+ model=model()
+ updateModelWithCFG(model)
+ return model
+
+ if hasattr(module, 'pymodel'):
+ model=module.pymodel
+ if callable(pymodel):
+ pymodel=pymodel()
+ updateModelWithCFG(pymodel.component)
+ return pymodel.component
+
+ if hasattr(module, 'model_src'):
+ model_src=module.model_src
+ if callable(model_src):
+ model_src=model_src()
+ from ModelSet import ModelSet
+ model=ModelSet().addModelFromXML({'string': model_src})
+ updateModelWithCFG(model)
+ return model
+
+ raise IOError, "Couldn't find any of these attributes in python file '%s': model, pymodel (PyModel) or model_src (xml)"%path
+
+ except:
+ import cStringIO, traceback
+ exc=cStringIO.StringIO()
+ traceback.print_exc(file=exc)
+ raise IOError, 'Unable to handle python file %s\nReason: exception raised:\n%s'%(path,exc.getvalue())
+
+ finally:
+ if file: file.close()
+ elif path[-4:]=='.xml':
+ from ModelSet import ModelSet
+ return ModelSet().addModelFromXML({'file': path})
+
+ else:
+ raise IOError, 'Unable to load file %s'%path
+
+ def searchModel(modelName, path=None, verbose=0):
+ """
+ Searches for the model named 'modelName' by trying loadModel() with the
+ following paths: 'pymodel_<modelName>.py', 'model_<modelName>.py' and
+ 'model_<modelName>.xml' in the current directory and the MDL/ directory.
+
+ Returns the model, or None if it cannot be found/loaded
+
+ """
+ if verbose:
+ import sys
+ mylog=lambda msg, stderr=sys.stderr:stderr.write('[Model.searchModel] %s\n'%msg)
+ else:
+ mylog=lambda msg: None
+
+ searchList=('pymodel_%s.py', 'model_%s.py', 'model_%s.xml',
+ 'MDL/pymodel_%s.py', 'MDL/model_%s.py', 'MDL/model_%s.xml')
+ for file in searchList:
+ model=None
+ file=file%modelName
+ if path:
+ import os
+ file=os.path.join(path, file)
+ try:
+ mylog('Trying %s'%file)
+ model=loadModel(file)
+ except IOError:
+ import cStringIO, traceback
+ exc=cStringIO.StringIO()
+ traceback.print_exc(file=exc)
+ mylog('Not found: %s\n Exception:%s'%(file,exc.getvalue()))
+ del exc
+ pass
+ if model:
+ return model
+ mylog('Not found: %s'%file)
+ mylog('modelName %s: All possibilities exhausted -- returning None'%modelName)
+ return None
+
class Model(Persistent, XMLCapability, KeyValueCoding):
"Describes a model"
|