summaryrefslogtreecommitdiff
path: root/django/urls/utils.py
diff options
context:
space:
mode:
authorMarten Kenbeek <marten.knbk@gmail.com>2015-12-30 16:51:16 +0100
committerTim Graham <timograham@gmail.com>2015-12-31 14:21:29 -0500
commit16411b8400ad08f90c236bb2e18f65c655f903f8 (patch)
treedf01123093c126222e8f492512472e5834966100 /django/urls/utils.py
parentdf3d5b1d73699b323aac377dffab039dca26c1e4 (diff)
downloaddjango-16411b8400ad08f90c236bb2e18f65c655f903f8.tar.gz
Fixed #26013 -- Moved django.core.urlresolvers to django.urls.
Thanks to Tim Graham for the review.
Diffstat (limited to 'django/urls/utils.py')
-rw-r--r--django/urls/utils.py64
1 files changed, 64 insertions, 0 deletions
diff --git a/django/urls/utils.py b/django/urls/utils.py
new file mode 100644
index 0000000000..1901c0a494
--- /dev/null
+++ b/django/urls/utils.py
@@ -0,0 +1,64 @@
+from __future__ import unicode_literals
+
+from importlib import import_module
+
+from django.core.exceptions import ViewDoesNotExist
+from django.utils import lru_cache, six
+from django.utils.module_loading import module_has_submodule
+
+
+@lru_cache.lru_cache(maxsize=None)
+def get_callable(lookup_view):
+ """
+ Return a callable corresponding to lookup_view.
+ * If lookup_view is already a callable, return it.
+ * If lookup_view is a string import path that can be resolved to a callable,
+ import that callable and return it, otherwise raise an exception
+ (ImportError or ViewDoesNotExist).
+ """
+ if callable(lookup_view):
+ return lookup_view
+
+ if not isinstance(lookup_view, six.string_types):
+ raise ViewDoesNotExist("'%s' is not a callable or a dot-notation path" % lookup_view)
+
+ mod_name, func_name = get_mod_func(lookup_view)
+ if not func_name: # No '.' in lookup_view
+ raise ImportError("Could not import '%s'. The path must be fully qualified." % lookup_view)
+
+ try:
+ mod = import_module(mod_name)
+ except ImportError:
+ parentmod, submod = get_mod_func(mod_name)
+ if submod and not module_has_submodule(import_module(parentmod), submod):
+ raise ViewDoesNotExist(
+ "Could not import '%s'. Parent module %s does not exist." %
+ (lookup_view, mod_name)
+ )
+ else:
+ raise
+ else:
+ try:
+ view_func = getattr(mod, func_name)
+ except AttributeError:
+ raise ViewDoesNotExist(
+ "Could not import '%s'. View does not exist in module %s." %
+ (lookup_view, mod_name)
+ )
+ else:
+ if not callable(view_func):
+ raise ViewDoesNotExist(
+ "Could not import '%s.%s'. View is not callable." %
+ (mod_name, func_name)
+ )
+ return view_func
+
+
+def get_mod_func(callback):
+ # Convert 'django.views.news.stories.story_detail' to
+ # ['django.views.news.stories', 'story_detail']
+ try:
+ dot = callback.rindex('.')
+ except ValueError:
+ return callback, ''
+ return callback[:dot], callback[dot + 1:]