2
# -*- coding: utf-8 -*-
8
# Install the new import function:
9
def custom_import_install(path):
10
_old__import__ = None # To keep the old __builtins__.__import__
12
re_escaped_path_sep = re.escape(os.path.sep) # os.path.sep escaped for re
14
# Regular expression to match a directory of a web2py application relative to
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(
20
"^" + re.escape(path),
27
def _web2py__import__(name, globals={}, locals={}, fromlist=[], level=-1):
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__
34
def _web2py__import__dot(prefix, name, globals, locals, fromlist, level):
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.
44
for name in name.split("."):
45
new_mod = _old__import__(prefix, globals, locals, [name], level)
47
result = result or new_mod.__dict__[name]
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)
65
# Get the prefix to add for the import
66
# (like applications.app_name.modules):
68
".".join((match_app_dir.group(1).replace(os.path.sep, "."),
71
# import like "import x" or "import x.y"
72
return _web2py__import__dot(modules_prefix, name, globals,
73
locals, fromlist, level)
75
# import like "from x import a, b, ..."
76
return _old__import__(modules_prefix + "." + name, globals,
77
locals, fromlist, level)
80
return _old__import__(name, globals, locals, fromlist, level)
82
(_old__import__, __builtin__.__import__) = (__builtin__.__import__, _web2py__import__)