1
2
3
4 import re
5 import os
6 import __builtin__
7
8
10 _old__import__ = None
11
12 re_escaped_path_sep = re.escape(os.path.sep)
13
14
15
16
17
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
54 if not name.startswith(".") and level <= 0 \
55 and not name.startswith("applications."):
56
57 caller_file_name = globals.get("__file__", "")
58 if not os.path.isabs(caller_file_name):
59
60 caller_file_name = os.path.join(path, caller_file_name)
61
62 match_app_dir = re_app_dir.match(caller_file_name)
63 if match_app_dir:
64 try:
65
66
67 modules_prefix = \
68 ".".join((match_app_dir.group(1).replace(os.path.sep, "."),
69 "modules"))
70 if not fromlist:
71
72 return _web2py__import__dot(modules_prefix, name, globals,
73 locals, fromlist, level)
74 else:
75
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