From b6429ca5fdbdc826e2fe071da927f5e64065c7bc Mon Sep 17 00:00:00 2001 From: mdipierro Date: Mon, 15 Oct 2012 05:46:57 -0500 Subject: [PATCH] better errors in custom_import, thanks Michele --- VERSION | 2 +- gluon/custom_import.py | 28 +++++++++++++++++++++------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/VERSION b/VERSION index 295ffe02..cb56b666 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.1.0 (2012-10-15 05:33:14) dev +Version 2.1.0 (2012-10-15 05:46:52) dev diff --git a/gluon/custom_import.py b/gluon/custom_import.py index 4ab746d8..af44308b 100644 --- a/gluon/custom_import.py +++ b/gluon/custom_import.py @@ -11,25 +11,30 @@ from gluon import current NATIVE_IMPORTER = __builtin__.__import__ TRACK_CHANGES = False -INVALID_MODULES = set(sys.modules.keys()).union(('','gluon','applications','custom_import')) +INVALID_MODULES = set(('','gluon','applications','custom_import')) -# backward compatibility API +# backward compatibility API def custom_import_install(): - __builtin__.__import__ = custom_importer + if __builtin__.__import__ != custom_importer: + INVALID_MODULES = INVALID_MODULES.union(sys.modules.keys()) + __builtin__.__import__ = custom_importer def track_changes(track=True): assert track in (True,False), "must be True or False" global TRACK_CHANGES TRACK_CHANGES = track -def is_tracking_changes(): +def is_tracking_changes(): return TRACK_CHANGES +class CustomImportException(ImportError): + pass + def custom_importer(name, globals=None, locals=None, fromlist=None, level=-1): """ The web2py custom importer. Like the standard Python importer but it tries to transform import statements as something like - "import applications.app_name.modules.x". + "import applications.app_name.modules.x". If the import failed, fall back on naive_importer """ @@ -43,7 +48,8 @@ def custom_importer(name, globals=None, locals=None, fromlist=None, level=-1): if hasattr(current,'request') \ and level<=0 \ and not name.split('.')[0] in INVALID_MODULES \ - and isinstance(globals, dict): + and isinstance(globals, dict): + import_tb = None try: items = current.request.folder.split(os.path.sep) if not items[-1]: items = items[:-1] @@ -65,9 +71,17 @@ def custom_importer(name, globals=None, locals=None, fromlist=None, level=-1): pname = modules_prefix + "." + name return base_importer(pname, globals, locals, fromlist, level) except ImportError, e1: - pass # the module does not exist + import_tb = sys.exc_info()[2] + try: + return NATIVE_IMPORTER(name,globals,locals,fromlist,level) + except ImportError, e3: + raise ImportError, e1, import_tb # there an import error in the module except Exception, e2: raise e2 # there is an error in the module + finally: + if import_tb: + import_tb = None + return NATIVE_IMPORTER(name,globals,locals,fromlist,level)