| 1 |
from importlib import import_module |
| 2 |
|
| 3 |
import django |
| 4 |
from django.apps import apps |
| 5 |
from django.core.exceptions import ImproperlyConfigured |
| 6 |
|
| 7 |
if django.VERSION >= (1, 10): |
| 8 |
from django.urls import reverse, NoReverseMatch |
| 9 |
else: |
| 10 |
from django.core.urlresolvers import reverse, NoReverseMatch |
| 11 |
|
| 12 |
|
| 13 |
def get_callable(func_or_path): |
| 14 |
""" |
| 15 |
Receives a dotted path or a callable, Returns a callable or None |
| 16 |
""" |
| 17 |
if callable(func_or_path): |
| 18 |
return func_or_path |
| 19 |
|
| 20 |
module_name = '.'.join(func_or_path.split('.')[:-1]) |
| 21 |
function_name = func_or_path.split('.')[-1] |
| 22 |
_module = import_module(module_name) |
| 23 |
func = getattr(_module, function_name) |
| 24 |
return func |
| 25 |
|
| 26 |
|
| 27 |
def clean_app_config(app_path): |
| 28 |
""" |
| 29 |
Removes the AppConfig path for this app and returns the new string |
| 30 |
""" |
| 31 |
apps_names = [app.name for app in apps.get_app_configs()] |
| 32 |
if app_path in apps_names: |
| 33 |
return app_path |
| 34 |
else: |
| 35 |
app_split = app_path.split('.') |
| 36 |
new_app = '.'.join(app_split[:-2]) |
| 37 |
if new_app in apps_names: |
| 38 |
return new_app |
| 39 |
else: |
| 40 |
raise ImproperlyConfigured( |
| 41 |
"The application {0} is not in the configured apps or does".format(app_path) + |
| 42 |
"not have the pattern app.apps.AppConfig" |
| 43 |
) |
| 44 |
|
| 45 |
|
| 46 |
def parse_url(url): |
| 47 |
""" |
| 48 |
Returns concrete URL for a menu dict URL attribute. |
| 49 |
""" |
| 50 |
try: |
| 51 |
final_url = reverse(**url) if type(url) is dict else reverse(url) |
| 52 |
except NoReverseMatch: |
| 53 |
final_url = url |
| 54 |
return final_url |
| 55 |
|
| 56 |
|
| 57 |
def path_startswith(path, prefix): |
| 58 |
""" |
| 59 |
Returns True if the leftmost path components are the same as prefix. |
| 60 |
""" |
| 61 |
path_components = path.strip("/").split("/") |
| 62 |
prefix_components = prefix.strip("/").split("/") |
| 63 |
|
| 64 |
return path_components[:len(prefix_components)] == prefix_components |