2005-07-13 09:25:57 +08:00
|
|
|
"""
|
|
|
|
This module converts requested URLs to callback view functions.
|
|
|
|
|
|
|
|
RegexURLResolver is the main class here. Its resolve() method takes a URL (as
|
|
|
|
a string) and returns a tuple in this format:
|
|
|
|
|
2005-11-28 06:08:51 +08:00
|
|
|
(view_function, function_args, function_kwargs)
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2014-04-23 04:19:46 +08:00
|
|
|
import functools
|
2013-07-29 21:50:58 +08:00
|
|
|
from importlib import import_module
|
2008-07-21 15:57:10 +08:00
|
|
|
import re
|
2011-01-17 17:52:47 +08:00
|
|
|
from threading import local
|
2014-06-03 19:30:14 +08:00
|
|
|
import warnings
|
2008-07-21 15:57:10 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.http import Http404
|
|
|
|
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
|
2008-09-27 14:14:11 +08:00
|
|
|
from django.utils.datastructures import MultiValueDict
|
2014-06-03 19:30:14 +08:00
|
|
|
from django.utils.deprecation import RemovedInDjango20Warning
|
2012-08-30 04:40:51 +08:00
|
|
|
from django.utils.encoding import force_str, force_text, iri_to_uri
|
2013-11-02 04:15:41 +08:00
|
|
|
from django.utils.functional import lazy
|
2014-06-26 22:55:36 +08:00
|
|
|
from django.utils.http import RFC3986_SUBDELIMS, urlquote
|
2011-06-17 00:41:14 +08:00
|
|
|
from django.utils.module_loading import module_has_submodule
|
2008-08-31 19:11:20 +08:00
|
|
|
from django.utils.regex_helper import normalize
|
2013-11-02 04:15:41 +08:00
|
|
|
from django.utils import six, lru_cache
|
2011-06-16 01:29:10 +08:00
|
|
|
from django.utils.translation import get_language
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2008-07-21 15:57:10 +08:00
|
|
|
# SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for
|
|
|
|
# the current thread (which is the only one we ever access), it is assumed to
|
|
|
|
# be empty.
|
2011-01-17 17:52:47 +08:00
|
|
|
_prefixes = local()
|
2008-07-21 15:57:10 +08:00
|
|
|
|
2009-11-16 09:58:00 +08:00
|
|
|
# Overridden URLconfs for each thread are stored here.
|
2011-01-17 17:52:47 +08:00
|
|
|
_urlconfs = local()
|
|
|
|
|
2009-11-16 09:58:00 +08:00
|
|
|
|
2010-08-05 15:09:47 +08:00
|
|
|
class ResolverMatch(object):
|
|
|
|
def __init__(self, func, args, kwargs, url_name=None, app_name=None, namespaces=None):
|
|
|
|
self.func = func
|
|
|
|
self.args = args
|
|
|
|
self.kwargs = kwargs
|
2013-10-03 15:20:04 +08:00
|
|
|
self.url_name = url_name
|
2010-08-05 15:09:47 +08:00
|
|
|
self.app_name = app_name
|
2013-10-03 15:20:04 +08:00
|
|
|
|
2010-08-05 15:09:47 +08:00
|
|
|
if namespaces:
|
|
|
|
self.namespaces = [x for x in namespaces if x]
|
|
|
|
else:
|
|
|
|
self.namespaces = []
|
2013-10-03 15:20:04 +08:00
|
|
|
self.namespace = ':'.join(self.namespaces)
|
2010-08-05 15:09:47 +08:00
|
|
|
|
2013-10-03 15:20:04 +08:00
|
|
|
if not hasattr(func, '__name__'):
|
|
|
|
# A class-based view
|
|
|
|
self._func_path = '.'.join([func.__class__.__module__, func.__class__.__name__])
|
|
|
|
else:
|
|
|
|
# A function-based view
|
|
|
|
self._func_path = '.'.join([func.__module__, func.__name__])
|
2010-08-05 15:09:47 +08:00
|
|
|
|
2013-10-03 15:20:04 +08:00
|
|
|
view_path = url_name or self._func_path
|
|
|
|
self.view_name = ':'.join(self.namespaces + [view_path])
|
2010-08-05 15:09:47 +08:00
|
|
|
|
|
|
|
def __getitem__(self, index):
|
|
|
|
return (self.func, self.args, self.kwargs)[index]
|
|
|
|
|
|
|
|
def __repr__(self):
|
2013-10-03 15:20:04 +08:00
|
|
|
return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_name=%s, namespaces=%s)" % (
|
|
|
|
self._func_path, self.args, self.kwargs, self.url_name, self.app_name, self.namespaces)
|
2010-08-05 15:09:47 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2005-08-06 06:22:41 +08:00
|
|
|
class Resolver404(Http404):
|
2014-02-16 00:45:16 +08:00
|
|
|
pass
|
2005-08-06 06:22:41 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-05-16 12:05:55 +08:00
|
|
|
class NoReverseMatch(Exception):
|
2013-05-30 15:25:58 +08:00
|
|
|
pass
|
2006-05-16 12:05:55 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-11-02 04:15:41 +08:00
|
|
|
@lru_cache.lru_cache(maxsize=None)
|
2007-06-25 12:34:34 +08:00
|
|
|
def get_callable(lookup_view, can_fail=False):
|
|
|
|
"""
|
2013-10-03 15:20:04 +08:00
|
|
|
Return a callable corresponding to lookup_view. This function is used
|
|
|
|
by both resolve() and reverse(), so can_fail allows the caller to choose
|
|
|
|
between returning the input as is and raising an exception when the input
|
|
|
|
string can't be interpreted as an import path.
|
|
|
|
|
|
|
|
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.
|
|
|
|
If lookup_view is some other kind of string and can_fail is True, the string
|
|
|
|
is returned as is. If can_fail is False, an exception is raised (either
|
|
|
|
ImportError or ViewDoesNotExist).
|
2007-06-25 12:34:34 +08:00
|
|
|
"""
|
2013-10-03 15:20:04 +08:00
|
|
|
if callable(lookup_view):
|
|
|
|
return lookup_view
|
2012-08-15 03:12:08 +08:00
|
|
|
|
2013-10-03 15:20:04 +08:00
|
|
|
mod_name, func_name = get_mod_func(lookup_view)
|
|
|
|
if not func_name: # No '.' in lookup_view
|
|
|
|
if can_fail:
|
|
|
|
return lookup_view
|
|
|
|
else:
|
|
|
|
raise ImportError(
|
|
|
|
"Could not import '%s'. The path must be fully qualified." %
|
|
|
|
lookup_view)
|
|
|
|
|
|
|
|
try:
|
|
|
|
mod = import_module(mod_name)
|
|
|
|
except ImportError:
|
|
|
|
if can_fail:
|
|
|
|
return lookup_view
|
|
|
|
else:
|
2011-06-17 15:39:03 +08:00
|
|
|
parentmod, submod = get_mod_func(mod_name)
|
2013-10-03 15:20:04 +08:00
|
|
|
if submod and not module_has_submodule(import_module(parentmod), submod):
|
2011-06-17 00:41:14 +08:00
|
|
|
raise ViewDoesNotExist(
|
2013-10-03 15:20:04 +08:00
|
|
|
"Could not import '%s'. Parent module %s does not exist." %
|
2011-08-12 22:15:50 +08:00
|
|
|
(lookup_view, mod_name))
|
2013-10-03 15:20:04 +08:00
|
|
|
else:
|
2007-07-08 08:39:32 +08:00
|
|
|
raise
|
2013-10-03 15:20:04 +08:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
view_func = getattr(mod, func_name)
|
|
|
|
except AttributeError:
|
|
|
|
if can_fail:
|
|
|
|
return lookup_view
|
|
|
|
else:
|
|
|
|
raise ViewDoesNotExist(
|
|
|
|
"Could not import '%s'. View does not exist in module %s." %
|
|
|
|
(lookup_view, mod_name))
|
2012-08-15 03:12:08 +08:00
|
|
|
else:
|
2013-10-03 15:20:04 +08:00
|
|
|
if not callable(view_func):
|
|
|
|
# For backwards compatibility this is raised regardless of can_fail
|
|
|
|
raise ViewDoesNotExist(
|
|
|
|
"Could not import '%s.%s'. View is not callable." %
|
|
|
|
(mod_name, func_name))
|
|
|
|
|
|
|
|
return view_func
|
2007-06-23 13:40:28 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-11-02 04:15:41 +08:00
|
|
|
@lru_cache.lru_cache(maxsize=None)
|
2007-06-23 13:40:28 +08:00
|
|
|
def get_resolver(urlconf):
|
|
|
|
if urlconf is None:
|
|
|
|
from django.conf import settings
|
|
|
|
urlconf = settings.ROOT_URLCONF
|
|
|
|
return RegexURLResolver(r'^/', urlconf)
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-11-02 04:15:41 +08:00
|
|
|
@lru_cache.lru_cache(maxsize=None)
|
2011-08-12 22:15:50 +08:00
|
|
|
def get_ns_resolver(ns_pattern, resolver):
|
|
|
|
# Build a namespaced resolver for the given parent urlconf pattern.
|
|
|
|
# This makes it possible to have captured parameters in the parent
|
|
|
|
# urlconf pattern.
|
2013-12-13 04:23:24 +08:00
|
|
|
ns_resolver = RegexURLResolver(ns_pattern, resolver.url_patterns)
|
2011-08-12 22:15:50 +08:00
|
|
|
return RegexURLResolver(r'^/', [ns_resolver])
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def get_mod_func(callback):
|
|
|
|
# Converts 'django.views.news.stories.story_detail' to
|
|
|
|
# ['django.views.news.stories', 'story_detail']
|
2006-11-07 13:05:16 +08:00
|
|
|
try:
|
|
|
|
dot = callback.rindex('.')
|
|
|
|
except ValueError:
|
|
|
|
return callback, ''
|
2013-11-04 02:08:55 +08:00
|
|
|
return callback[:dot], callback[dot + 1:]
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
class LocaleRegexProvider(object):
|
|
|
|
"""
|
|
|
|
A mixin to provide a default regex property which can vary by active
|
|
|
|
language.
|
|
|
|
|
|
|
|
"""
|
|
|
|
def __init__(self, regex):
|
|
|
|
# regex is either a string representing a regular expression, or a
|
|
|
|
# translatable string (using ugettext_lazy) representing a regular
|
|
|
|
# expression.
|
|
|
|
self._regex = regex
|
|
|
|
self._regex_dict = {}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def regex(self):
|
|
|
|
"""
|
|
|
|
Returns a compiled regular expression, depending upon the activated
|
|
|
|
language-code.
|
|
|
|
"""
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._regex_dict:
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(self._regex, six.string_types):
|
2012-07-22 04:30:34 +08:00
|
|
|
regex = self._regex
|
2011-06-16 01:29:10 +08:00
|
|
|
else:
|
2012-07-21 16:00:10 +08:00
|
|
|
regex = force_text(self._regex)
|
2012-07-22 04:30:34 +08:00
|
|
|
try:
|
2011-06-16 01:29:10 +08:00
|
|
|
compiled_regex = re.compile(regex, re.UNICODE)
|
2012-07-22 06:13:55 +08:00
|
|
|
except re.error as e:
|
2012-07-22 04:30:34 +08:00
|
|
|
raise ImproperlyConfigured(
|
2012-07-22 04:38:25 +08:00
|
|
|
'"%s" is not a valid regular expression: %s' %
|
2012-07-20 20:48:51 +08:00
|
|
|
(regex, six.text_type(e)))
|
2012-07-22 04:30:34 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
self._regex_dict[language_code] = compiled_regex
|
|
|
|
return self._regex_dict[language_code]
|
|
|
|
|
|
|
|
|
|
|
|
class RegexURLPattern(LocaleRegexProvider):
|
2007-04-01 15:25:20 +08:00
|
|
|
def __init__(self, regex, callback, default_args=None, name=None):
|
2011-06-16 01:29:10 +08:00
|
|
|
LocaleRegexProvider.__init__(self, regex)
|
2006-08-11 15:01:29 +08:00
|
|
|
# callback is either a string like 'foo.views.news.stories.story_detail'
|
|
|
|
# which represents the path to a module and a view function name, or a
|
|
|
|
# callable object (view).
|
|
|
|
if callable(callback):
|
|
|
|
self._callback = callback
|
|
|
|
else:
|
|
|
|
self._callback = None
|
|
|
|
self._callback_str = callback
|
2005-07-13 09:25:57 +08:00
|
|
|
self.default_args = default_args or {}
|
2007-04-01 15:25:20 +08:00
|
|
|
self.name = name
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-07-13 17:14:51 +08:00
|
|
|
def __repr__(self):
|
2012-08-30 04:40:51 +08:00
|
|
|
return force_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))
|
2007-07-13 17:14:51 +08:00
|
|
|
|
2007-04-26 19:17:19 +08:00
|
|
|
def add_prefix(self, prefix):
|
|
|
|
"""
|
|
|
|
Adds the prefix string to a string-based callback.
|
|
|
|
"""
|
|
|
|
if not prefix or not hasattr(self, '_callback_str'):
|
|
|
|
return
|
|
|
|
self._callback_str = prefix + '.' + self._callback_str
|
|
|
|
|
2005-08-06 04:50:19 +08:00
|
|
|
def resolve(self, path):
|
2005-07-13 09:25:57 +08:00
|
|
|
match = self.regex.search(path)
|
|
|
|
if match:
|
2005-11-28 06:08:51 +08:00
|
|
|
# If there are any named groups, use those as kwargs, ignoring
|
|
|
|
# non-named groups. Otherwise, pass all non-named arguments as
|
|
|
|
# positional arguments.
|
|
|
|
kwargs = match.groupdict()
|
|
|
|
if kwargs:
|
|
|
|
args = ()
|
2007-02-26 06:31:31 +08:00
|
|
|
else:
|
2005-11-28 06:08:51 +08:00
|
|
|
args = match.groups()
|
|
|
|
# In both cases, pass any extra_kwargs as **kwargs.
|
|
|
|
kwargs.update(self.default_args)
|
|
|
|
|
2010-08-05 15:09:47 +08:00
|
|
|
return ResolverMatch(self.callback, args, kwargs, self.name)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
@property
|
|
|
|
def callback(self):
|
2006-08-11 15:01:29 +08:00
|
|
|
if self._callback is not None:
|
|
|
|
return self._callback
|
2011-06-17 00:41:14 +08:00
|
|
|
|
|
|
|
self._callback = get_callable(self._callback_str)
|
2006-08-11 15:01:29 +08:00
|
|
|
return self._callback
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
class RegexURLResolver(LocaleRegexProvider):
|
2009-07-17 00:16:13 +08:00
|
|
|
def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
|
2011-06-16 01:29:10 +08:00
|
|
|
LocaleRegexProvider.__init__(self, regex)
|
2009-04-01 00:07:07 +08:00
|
|
|
# urlconf_name is a string representing the module containing URLconfs.
|
2005-08-06 04:50:19 +08:00
|
|
|
self.urlconf_name = urlconf_name
|
2012-07-20 20:22:00 +08:00
|
|
|
if not isinstance(urlconf_name, six.string_types):
|
2009-01-11 06:54:20 +08:00
|
|
|
self._urlconf_module = self.urlconf_name
|
2006-05-16 12:05:55 +08:00
|
|
|
self.callback = None
|
2006-08-01 10:57:08 +08:00
|
|
|
self.default_kwargs = default_kwargs or {}
|
2009-07-17 00:16:13 +08:00
|
|
|
self.namespace = namespace
|
|
|
|
self.app_name = app_name
|
2011-06-16 01:29:10 +08:00
|
|
|
self._reverse_dict = {}
|
|
|
|
self._namespace_dict = {}
|
|
|
|
self._app_dict = {}
|
2014-04-21 01:12:43 +08:00
|
|
|
# set of dotted paths to all functions and classes that are used in
|
|
|
|
# urlpatterns
|
|
|
|
self._callback_strs = set()
|
|
|
|
self._populated = False
|
2007-06-24 17:38:30 +08:00
|
|
|
|
2007-07-13 17:14:51 +08:00
|
|
|
def __repr__(self):
|
2012-09-02 04:07:18 +08:00
|
|
|
if isinstance(self.urlconf_name, list) and len(self.urlconf_name):
|
|
|
|
# Don't bother to output the whole list, it can be huge
|
|
|
|
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
|
|
|
|
else:
|
|
|
|
urlconf_repr = repr(self.urlconf_name)
|
2012-12-08 18:13:52 +08:00
|
|
|
return str('<%s %s (%s:%s) %s>') % (
|
2012-09-02 04:07:18 +08:00
|
|
|
self.__class__.__name__, urlconf_repr, self.app_name,
|
2012-12-08 18:13:52 +08:00
|
|
|
self.namespace, self.regex.pattern)
|
2009-07-17 00:16:13 +08:00
|
|
|
|
|
|
|
def _populate(self):
|
|
|
|
lookups = MultiValueDict()
|
|
|
|
namespaces = {}
|
|
|
|
apps = {}
|
2011-06-16 01:29:10 +08:00
|
|
|
language_code = get_language()
|
2009-07-17 00:16:13 +08:00
|
|
|
for pattern in reversed(self.url_patterns):
|
2014-04-21 01:12:43 +08:00
|
|
|
if hasattr(pattern, '_callback_str'):
|
|
|
|
self._callback_strs.add(pattern._callback_str)
|
|
|
|
elif hasattr(pattern, '_callback'):
|
|
|
|
callback = pattern._callback
|
2014-04-23 04:19:46 +08:00
|
|
|
if isinstance(callback, functools.partial):
|
|
|
|
callback = callback.func
|
|
|
|
|
2014-04-21 01:12:43 +08:00
|
|
|
if not hasattr(callback, '__name__'):
|
|
|
|
lookup_str = callback.__module__ + "." + callback.__class__.__name__
|
|
|
|
else:
|
|
|
|
lookup_str = callback.__module__ + "." + callback.__name__
|
|
|
|
self._callback_strs.add(lookup_str)
|
2009-07-17 00:16:13 +08:00
|
|
|
p_pattern = pattern.regex.pattern
|
|
|
|
if p_pattern.startswith('^'):
|
|
|
|
p_pattern = p_pattern[1:]
|
|
|
|
if isinstance(pattern, RegexURLResolver):
|
|
|
|
if pattern.namespace:
|
|
|
|
namespaces[pattern.namespace] = (p_pattern, pattern)
|
|
|
|
if pattern.app_name:
|
|
|
|
apps.setdefault(pattern.app_name, []).append(pattern.namespace)
|
|
|
|
else:
|
2014-02-27 23:32:20 +08:00
|
|
|
parent_pat = pattern.regex.pattern
|
2008-09-30 13:52:35 +08:00
|
|
|
for name in pattern.reverse_dict:
|
2011-05-08 00:59:25 +08:00
|
|
|
for matches, pat, defaults in pattern.reverse_dict.getlist(name):
|
2014-02-27 23:32:20 +08:00
|
|
|
new_matches = normalize(parent_pat + pat)
|
2014-09-04 20:15:09 +08:00
|
|
|
lookups.appendlist(
|
|
|
|
name,
|
|
|
|
(
|
|
|
|
new_matches,
|
|
|
|
p_pattern + pat,
|
|
|
|
dict(defaults, **pattern.default_kwargs),
|
|
|
|
)
|
|
|
|
)
|
2009-07-17 00:16:13 +08:00
|
|
|
for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items():
|
|
|
|
namespaces[namespace] = (p_pattern + prefix, sub_pattern)
|
|
|
|
for app_name, namespace_list in pattern.app_dict.items():
|
|
|
|
apps.setdefault(app_name, []).extend(namespace_list)
|
2014-04-21 01:12:43 +08:00
|
|
|
self._callback_strs.update(pattern._callback_strs)
|
2009-07-17 00:16:13 +08:00
|
|
|
else:
|
|
|
|
bits = normalize(p_pattern)
|
2011-05-08 00:59:25 +08:00
|
|
|
lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args))
|
2010-08-06 22:34:10 +08:00
|
|
|
if pattern.name is not None:
|
2011-05-08 00:59:25 +08:00
|
|
|
lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args))
|
2011-06-16 01:29:10 +08:00
|
|
|
self._reverse_dict[language_code] = lookups
|
|
|
|
self._namespace_dict[language_code] = namespaces
|
|
|
|
self._app_dict[language_code] = apps
|
2014-04-21 01:12:43 +08:00
|
|
|
self._populated = True
|
2011-06-16 01:29:10 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def reverse_dict(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._reverse_dict:
|
2009-07-17 00:16:13 +08:00
|
|
|
self._populate()
|
2011-06-16 01:29:10 +08:00
|
|
|
return self._reverse_dict[language_code]
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
@property
|
|
|
|
def namespace_dict(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._namespace_dict:
|
2009-07-17 00:16:13 +08:00
|
|
|
self._populate()
|
2011-06-16 01:29:10 +08:00
|
|
|
return self._namespace_dict[language_code]
|
2009-07-17 00:16:13 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
@property
|
|
|
|
def app_dict(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._app_dict:
|
2009-07-17 00:16:13 +08:00
|
|
|
self._populate()
|
2011-06-16 01:29:10 +08:00
|
|
|
return self._app_dict[language_code]
|
2009-07-17 00:16:13 +08:00
|
|
|
|
2014-10-05 01:04:21 +08:00
|
|
|
def _is_callback(self, name):
|
|
|
|
if not self._populated:
|
|
|
|
self._populate()
|
|
|
|
return name in self._callback_strs
|
|
|
|
|
2005-08-06 04:50:19 +08:00
|
|
|
def resolve(self, path):
|
2013-09-07 02:43:58 +08:00
|
|
|
path = force_text(path) # path may be a reverse_lazy object
|
2005-08-06 06:22:41 +08:00
|
|
|
tried = []
|
2005-07-13 09:25:57 +08:00
|
|
|
match = self.regex.search(path)
|
|
|
|
if match:
|
|
|
|
new_path = path[match.end():]
|
2009-01-11 06:54:20 +08:00
|
|
|
for pattern in self.url_patterns:
|
2005-08-06 06:22:41 +08:00
|
|
|
try:
|
|
|
|
sub_match = pattern.resolve(new_path)
|
2012-04-29 00:09:37 +08:00
|
|
|
except Resolver404 as e:
|
2014-02-16 00:45:16 +08:00
|
|
|
sub_tried = e.args[0].get('tried')
|
2009-07-02 22:02:58 +08:00
|
|
|
if sub_tried is not None:
|
2013-08-30 07:20:00 +08:00
|
|
|
tried.extend([pattern] + t for t in sub_tried)
|
2009-07-02 22:02:58 +08:00
|
|
|
else:
|
2010-09-13 03:27:33 +08:00
|
|
|
tried.append([pattern])
|
2005-08-06 06:22:41 +08:00
|
|
|
else:
|
|
|
|
if sub_match:
|
2012-05-24 19:47:40 +08:00
|
|
|
sub_match_dict = dict(match.groupdict(), **self.default_kwargs)
|
|
|
|
sub_match_dict.update(sub_match.kwargs)
|
2014-09-04 20:15:09 +08:00
|
|
|
return ResolverMatch(
|
|
|
|
sub_match.func,
|
|
|
|
sub_match.args,
|
|
|
|
sub_match_dict,
|
|
|
|
sub_match.url_name,
|
|
|
|
self.app_name or sub_match.app_name,
|
|
|
|
[self.namespace] + sub_match.namespaces
|
|
|
|
)
|
2010-09-13 03:27:33 +08:00
|
|
|
tried.append([pattern])
|
2014-02-16 00:45:16 +08:00
|
|
|
raise Resolver404({'tried': tried, 'path': new_path})
|
|
|
|
raise Resolver404({'path': path})
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
@property
|
|
|
|
def urlconf_module(self):
|
2005-08-11 06:20:18 +08:00
|
|
|
try:
|
|
|
|
return self._urlconf_module
|
|
|
|
except AttributeError:
|
2009-03-19 00:55:59 +08:00
|
|
|
self._urlconf_module = import_module(self.urlconf_name)
|
2005-08-11 06:20:18 +08:00
|
|
|
return self._urlconf_module
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
@property
|
|
|
|
def url_patterns(self):
|
2014-02-22 22:36:49 +08:00
|
|
|
# urlconf_module might be a valid set of patterns, so we default to it
|
2009-01-11 06:54:20 +08:00
|
|
|
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
|
|
|
|
try:
|
|
|
|
iter(patterns)
|
|
|
|
except TypeError:
|
2014-02-22 22:36:49 +08:00
|
|
|
msg = (
|
|
|
|
"The included urlconf '{name}' does not appear to have any "
|
|
|
|
"patterns in it. If you see valid patterns in the file then "
|
|
|
|
"the issue is probably caused by a circular import."
|
|
|
|
)
|
|
|
|
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
|
2009-01-11 06:54:20 +08:00
|
|
|
return patterns
|
2005-09-29 21:29:12 +08:00
|
|
|
|
2014-06-22 11:32:14 +08:00
|
|
|
def resolve_error_handler(self, view_type):
|
2010-08-14 22:27:35 +08:00
|
|
|
callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
|
|
|
|
if not callback:
|
|
|
|
# No handler specified in file; use default
|
2011-10-29 20:24:44 +08:00
|
|
|
# Lazy import, since django.urls imports this file
|
2011-10-29 05:23:50 +08:00
|
|
|
from django.conf import urls
|
|
|
|
callback = getattr(urls, 'handler%s' % view_type)
|
2011-06-17 00:41:14 +08:00
|
|
|
return get_callable(callback), {}
|
2005-08-06 04:50:19 +08:00
|
|
|
|
2006-08-11 15:01:29 +08:00
|
|
|
def reverse(self, lookup_view, *args, **kwargs):
|
2011-12-23 07:03:48 +08:00
|
|
|
return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)
|
|
|
|
|
|
|
|
def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
|
2008-08-31 19:11:20 +08:00
|
|
|
if args and kwargs:
|
|
|
|
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
|
2013-03-19 04:52:16 +08:00
|
|
|
text_args = [force_text(v) for v in args]
|
2014-12-07 05:00:09 +08:00
|
|
|
text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()}
|
2013-03-19 04:52:16 +08:00
|
|
|
|
2014-04-21 01:12:43 +08:00
|
|
|
if not self._populated:
|
|
|
|
self._populate()
|
|
|
|
|
2014-06-03 19:30:14 +08:00
|
|
|
original_lookup = lookup_view
|
2007-06-23 13:40:28 +08:00
|
|
|
try:
|
2014-10-05 01:04:21 +08:00
|
|
|
if self._is_callback(lookup_view):
|
2014-04-21 01:12:43 +08:00
|
|
|
lookup_view = get_callable(lookup_view, True)
|
2012-04-29 00:09:37 +08:00
|
|
|
except (ImportError, AttributeError) as e:
|
2008-08-29 03:05:14 +08:00
|
|
|
raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
|
2014-06-03 19:30:14 +08:00
|
|
|
else:
|
|
|
|
if not callable(original_lookup) and callable(lookup_view):
|
|
|
|
warnings.warn(
|
|
|
|
'Reversing by dotted path is deprecated (%s).' % original_lookup,
|
|
|
|
RemovedInDjango20Warning, stacklevel=3
|
|
|
|
)
|
2008-09-27 14:14:11 +08:00
|
|
|
possibilities = self.reverse_dict.getlist(lookup_view)
|
2012-11-04 04:06:57 +08:00
|
|
|
|
|
|
|
prefix_norm, prefix_args = normalize(urlquote(_prefix))[0]
|
2011-05-08 00:59:25 +08:00
|
|
|
for possibility, pattern, defaults in possibilities:
|
2008-09-27 14:14:11 +08:00
|
|
|
for result, params in possibility:
|
|
|
|
if args:
|
2011-12-23 07:03:48 +08:00
|
|
|
if len(args) != len(params) + len(prefix_args):
|
2008-09-27 14:14:11 +08:00
|
|
|
continue
|
2013-03-19 04:52:16 +08:00
|
|
|
candidate_subs = dict(zip(prefix_args + params, text_args))
|
2008-09-27 14:14:11 +08:00
|
|
|
else:
|
2014-09-04 20:15:09 +08:00
|
|
|
if (set(kwargs.keys()) | set(defaults.keys()) != set(params) |
|
|
|
|
set(defaults.keys()) | set(prefix_args)):
|
2011-05-08 00:59:25 +08:00
|
|
|
continue
|
|
|
|
matches = True
|
|
|
|
for k, v in defaults.items():
|
|
|
|
if kwargs.get(k, v) != v:
|
|
|
|
matches = False
|
|
|
|
break
|
|
|
|
if not matches:
|
2008-09-27 14:14:11 +08:00
|
|
|
continue
|
2013-03-19 04:52:16 +08:00
|
|
|
candidate_subs = text_kwargs
|
|
|
|
# WSGI provides decoded URLs, without %xx escapes, and the URL
|
|
|
|
# resolver operates on such URLs. First substitute arguments
|
|
|
|
# without quoting to build a decoded URL and look for a match.
|
|
|
|
# Then, if we have a match, redo the substitution with quoted
|
|
|
|
# arguments in order to return a properly encoded URL.
|
|
|
|
candidate_pat = prefix_norm.replace('%', '%%') + result
|
|
|
|
if re.search('^%s%s' % (prefix_norm, pattern), candidate_pat % candidate_subs, re.UNICODE):
|
2014-06-26 22:55:36 +08:00
|
|
|
# safe characters from `pchar` definition of RFC 3986
|
|
|
|
candidate_subs = dict((k, urlquote(v, safe=RFC3986_SUBDELIMS + str('/~:@')))
|
|
|
|
for (k, v) in candidate_subs.items())
|
2014-07-18 03:59:28 +08:00
|
|
|
url = candidate_pat % candidate_subs
|
|
|
|
# Don't allow construction of scheme relative urls.
|
|
|
|
if url.startswith('//'):
|
|
|
|
url = '/%%2F%s' % url[2:]
|
|
|
|
return url
|
2009-09-10 19:08:16 +08:00
|
|
|
# lookup_view can be URL label, or dotted path, or callable, Any of
|
|
|
|
# these can be passed in at the top, but callables are not friendly in
|
|
|
|
# error messages.
|
|
|
|
m = getattr(lookup_view, '__module__', None)
|
|
|
|
n = getattr(lookup_view, '__name__', None)
|
|
|
|
if m is not None and n is not None:
|
|
|
|
lookup_view_s = "%s.%s" % (m, n)
|
|
|
|
else:
|
|
|
|
lookup_view_s = lookup_view
|
2013-06-13 20:55:18 +08:00
|
|
|
|
|
|
|
patterns = [pattern for (possibility, pattern, defaults) in possibilities]
|
2008-08-29 03:05:14 +08:00
|
|
|
raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword "
|
2013-06-13 20:55:18 +08:00
|
|
|
"arguments '%s' not found. %d pattern(s) tried: %s" %
|
|
|
|
(lookup_view_s, args, kwargs, len(patterns), patterns))
|
2006-06-02 12:38:16 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
class LocaleRegexURLResolver(RegexURLResolver):
|
|
|
|
"""
|
|
|
|
A URL resolver that always matches the active language code as URL prefix.
|
|
|
|
|
|
|
|
Rather than taking a regex argument, we just override the ``regex``
|
|
|
|
function to always return the active language-code as regex.
|
|
|
|
"""
|
|
|
|
def __init__(self, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
|
|
|
|
super(LocaleRegexURLResolver, self).__init__(
|
|
|
|
None, urlconf_name, default_kwargs, app_name, namespace)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def regex(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._regex_dict:
|
|
|
|
regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
|
|
|
|
self._regex_dict[language_code] = regex_compiled
|
|
|
|
return self._regex_dict[language_code]
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-07-25 15:30:22 +08:00
|
|
|
def resolve(path, urlconf=None):
|
2009-11-16 09:58:00 +08:00
|
|
|
if urlconf is None:
|
|
|
|
urlconf = get_urlconf()
|
2007-06-23 13:40:28 +08:00
|
|
|
return get_resolver(urlconf).resolve(path)
|
2006-07-25 15:30:22 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-07-17 00:16:13 +08:00
|
|
|
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
|
2009-11-16 09:58:00 +08:00
|
|
|
if urlconf is None:
|
|
|
|
urlconf = get_urlconf()
|
2009-07-17 00:16:13 +08:00
|
|
|
resolver = get_resolver(urlconf)
|
2006-07-25 15:30:22 +08:00
|
|
|
args = args or []
|
|
|
|
kwargs = kwargs or {}
|
2009-07-17 00:16:13 +08:00
|
|
|
|
2008-07-21 15:57:10 +08:00
|
|
|
if prefix is None:
|
|
|
|
prefix = get_script_prefix()
|
2009-07-17 00:16:13 +08:00
|
|
|
|
2012-07-20 20:22:00 +08:00
|
|
|
if not isinstance(viewname, six.string_types):
|
2009-07-17 00:16:13 +08:00
|
|
|
view = viewname
|
|
|
|
else:
|
|
|
|
parts = viewname.split(':')
|
|
|
|
parts.reverse()
|
|
|
|
view = parts[0]
|
|
|
|
path = parts[1:]
|
|
|
|
|
|
|
|
resolved_path = []
|
2011-08-12 22:15:50 +08:00
|
|
|
ns_pattern = ''
|
2009-07-17 00:16:13 +08:00
|
|
|
while path:
|
|
|
|
ns = path.pop()
|
|
|
|
|
|
|
|
# Lookup the name to see if it could be an app identifier
|
|
|
|
try:
|
|
|
|
app_list = resolver.app_dict[ns]
|
|
|
|
# Yes! Path part matches an app in the current Resolver
|
|
|
|
if current_app and current_app in app_list:
|
2011-08-12 22:15:50 +08:00
|
|
|
# If we are reversing for a particular app,
|
|
|
|
# use that namespace
|
2009-07-17 00:16:13 +08:00
|
|
|
ns = current_app
|
|
|
|
elif ns not in app_list:
|
2011-08-12 22:15:50 +08:00
|
|
|
# The name isn't shared by one of the instances
|
|
|
|
# (i.e., the default) so just pick the first instance
|
|
|
|
# as the default.
|
2009-07-17 00:16:13 +08:00
|
|
|
ns = app_list[0]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
try:
|
|
|
|
extra, resolver = resolver.namespace_dict[ns]
|
|
|
|
resolved_path.append(ns)
|
2011-08-12 22:15:50 +08:00
|
|
|
ns_pattern = ns_pattern + extra
|
2012-04-29 00:09:37 +08:00
|
|
|
except KeyError as key:
|
2009-07-17 00:16:13 +08:00
|
|
|
if resolved_path:
|
2011-08-12 22:15:50 +08:00
|
|
|
raise NoReverseMatch(
|
|
|
|
"%s is not a registered namespace inside '%s'" %
|
|
|
|
(key, ':'.join(resolved_path)))
|
2009-07-17 00:16:13 +08:00
|
|
|
else:
|
2011-08-12 22:15:50 +08:00
|
|
|
raise NoReverseMatch("%s is not a registered namespace" %
|
|
|
|
key)
|
|
|
|
if ns_pattern:
|
|
|
|
resolver = get_ns_resolver(ns_pattern, resolver)
|
2009-07-17 00:16:13 +08:00
|
|
|
|
2014-09-19 04:03:09 +08:00
|
|
|
return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
|
2007-06-23 13:40:28 +08:00
|
|
|
|
2014-09-19 04:03:09 +08:00
|
|
|
reverse_lazy = lazy(reverse, six.text_type)
|
2011-04-29 19:49:59 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-06-30 20:34:29 +08:00
|
|
|
def clear_url_caches():
|
2013-11-02 04:15:41 +08:00
|
|
|
get_callable.cache_clear()
|
|
|
|
get_resolver.cache_clear()
|
|
|
|
get_ns_resolver.cache_clear()
|
2008-07-21 15:57:10 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-07-21 15:57:10 +08:00
|
|
|
def set_script_prefix(prefix):
|
|
|
|
"""
|
|
|
|
Sets the script prefix for the current thread.
|
|
|
|
"""
|
|
|
|
if not prefix.endswith('/'):
|
|
|
|
prefix += '/'
|
2011-01-17 17:52:47 +08:00
|
|
|
_prefixes.value = prefix
|
2008-07-21 15:57:10 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-07-21 15:57:10 +08:00
|
|
|
def get_script_prefix():
|
|
|
|
"""
|
|
|
|
Returns the currently active script prefix. Useful for client code that
|
|
|
|
wishes to construct their own URLs manually (although accessing the request
|
|
|
|
instance is normally going to be a lot cleaner).
|
|
|
|
"""
|
2012-06-08 00:08:47 +08:00
|
|
|
return getattr(_prefixes, "value", '/')
|
2008-07-21 15:57:10 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-02-24 20:25:17 +08:00
|
|
|
def clear_script_prefix():
|
|
|
|
"""
|
|
|
|
Unsets the script prefix for the current thread.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
del _prefixes.value
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-11-16 09:58:00 +08:00
|
|
|
def set_urlconf(urlconf_name):
|
|
|
|
"""
|
|
|
|
Sets the URLconf for the current thread (overriding the default one in
|
|
|
|
settings). Set to None to revert back to the default.
|
|
|
|
"""
|
|
|
|
if urlconf_name:
|
2011-01-17 17:52:47 +08:00
|
|
|
_urlconfs.value = urlconf_name
|
2009-11-16 09:58:00 +08:00
|
|
|
else:
|
2011-01-17 17:52:47 +08:00
|
|
|
if hasattr(_urlconfs, "value"):
|
|
|
|
del _urlconfs.value
|
2009-11-16 09:58:00 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-11-16 09:58:00 +08:00
|
|
|
def get_urlconf(default=None):
|
|
|
|
"""
|
|
|
|
Returns the root URLconf to use for the current thread if it has been
|
|
|
|
changed from the default one.
|
|
|
|
"""
|
2011-01-17 17:52:47 +08:00
|
|
|
return getattr(_urlconfs, "value", default)
|
2012-03-02 19:07:36 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2012-03-02 19:07:36 +08:00
|
|
|
def is_valid_path(path, urlconf=None):
|
|
|
|
"""
|
|
|
|
Returns True if the given path resolves against the default URL resolver,
|
|
|
|
False otherwise.
|
|
|
|
|
|
|
|
This is a convenience method to make working with "is this a match?" cases
|
|
|
|
easier, avoiding unnecessarily indented try...except blocks.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
resolve(path, urlconf)
|
|
|
|
return True
|
|
|
|
except Resolver404:
|
|
|
|
return False
|