-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathutils.py
34 lines (31 loc) · 1 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from django.core.exceptions import ImproperlyConfigured
def importpath(path, error_text=None):
"""
Import value by specified ``path``.
Value can represent module, class, object, attribute or method.
If ``error_text`` is not None and import will
raise ImproperlyConfigured with user friendly text.
"""
result = None
attrs = []
parts = path.split(".")
exception = None
while parts:
try:
result = __import__(".".join(parts), {}, {}, [""])
except ImportError as e:
if exception is None:
exception = e
attrs = parts[-1:] + attrs
parts = parts[:-1]
else:
break
for attr in attrs:
try:
result = getattr(result, attr)
except (AttributeError, ValueError) as e:
if error_text is not None:
raise ImproperlyConfigured(f'Error: {error_text} can import "{path}"')
else:
raise exception
return result