Package web2py :: Package gluon :: Module custom_import
[hide private]
[frames] | no frames]

Source Code for Module web2py.gluon.custom_import

 1  #!/usr/bin/env python 
 2  # -*- coding: utf-8 -*- 
 3   
 4  import re 
 5  import os 
 6  import __builtin__ 
 7   
 8  # Install the new import function:  
9 -def custom_import_install(path):
10 _old__import__ = None # To keep the old __builtins__.__import__ 11 12 re_escaped_path_sep = re.escape(os.path.sep) # os.path.sep escaped for re 13 14 # Regular expression to match a directory of a web2py application relative to 15 # the web2py install. 16 # Like web2py installation dir path/applications/app_name/modules. 17 # We also capture "applications/app_name" as a group. 18 re_app_dir = re.compile(re_escaped_path_sep.join( 19 ( 20 "^" + re.escape(path), 21 "(" + "applications", 22 "[^", 23 "]+)", 24 "", 25 ) )) 26 27 def _web2py__import__(name, globals={}, locals={}, fromlist=[], level=-1): 28 """ 29 This new import function will try to import from applications.module. 30 If this does not work, it falls back on the regular import method. 31 @see: __builtins__.__import__ 32 """ 33 34 def _web2py__import__dot(prefix, name, globals, locals, fromlist, level): 35 """ 36 Here we will import x.y.z as many imports like: 37 from applications.app_name.modules import x 38 from applications.app_name.modules.x import y 39 from applications.app_name.modules.x.y import z. 40 x will be the module returned. 41 """ 42 43 result = None 44 for name in name.split("."): 45 new_mod = _old__import__(prefix, globals, locals, [name], level) 46 try: 47 result = result or new_mod.__dict__[name] 48 except KeyError: 49 raise ImportError() 50 prefix += "." + name 51 return result
52 53 # if not relative and not from applications: 54 if not name.startswith(".") and level <= 0 \ 55 and not name.startswith("applications."): 56 # Get the name of the file do the import 57 caller_file_name = globals.get("__file__", "") 58 if not os.path.isabs(caller_file_name): 59 # Make the path absolute 60 caller_file_name = os.path.join(path, caller_file_name) 61 # Is the path in an application directory? 62 match_app_dir = re_app_dir.match(caller_file_name) 63 if match_app_dir: 64 try: 65 # Get the prefix to add for the import 66 # (like applications.app_name.modules): 67 modules_prefix = \ 68 ".".join((match_app_dir.group(1).replace(os.path.sep, "."), 69 "modules")) 70 if not fromlist: 71 # import like "import x" or "import x.y" 72 return _web2py__import__dot(modules_prefix, name, globals, 73 locals, fromlist, level) 74 else: 75 # import like "from x import a, b, ..." 76 return _old__import__(modules_prefix + "." + name, globals, 77 locals, fromlist, level) 78 except ImportError: 79 pass 80 return _old__import__(name, globals, locals, fromlist, level) 81 82 (_old__import__, __builtin__.__import__) = (__builtin__.__import__, _web2py__import__) 83