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
|
|
|
"""
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.http import Http404
|
|
|
|
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
from django.utils.encoding import iri_to_uri
|
2007-06-23 13:40:28 +08:00
|
|
|
from django.utils.functional import memoize
|
2005-07-13 09:25:57 +08:00
|
|
|
import re
|
|
|
|
|
2007-06-23 14:02:17 +08:00
|
|
|
try:
|
|
|
|
reversed
|
|
|
|
except NameError:
|
|
|
|
from django.utils.itercompat import reversed # Python 2.3 fallback
|
|
|
|
|
2007-06-23 13:40:28 +08:00
|
|
|
_resolver_cache = {} # Maps urlconf modules to RegexURLResolver instances.
|
|
|
|
_callable_cache = {} # Maps view and url pattern names to their view functions.
|
|
|
|
|
2005-08-06 06:22:41 +08:00
|
|
|
class Resolver404(Http404):
|
|
|
|
pass
|
|
|
|
|
2006-05-16 12:05:55 +08:00
|
|
|
class NoReverseMatch(Exception):
|
2006-10-10 07:24:48 +08:00
|
|
|
# Don't make this raise an error when used in a template.
|
2007-02-26 06:31:31 +08:00
|
|
|
silent_variable_failure = True
|
2006-05-16 12:05:55 +08:00
|
|
|
|
2007-06-25 12:34:34 +08:00
|
|
|
def get_callable(lookup_view, can_fail=False):
|
|
|
|
"""
|
|
|
|
Convert a string version of a function name to the callable object.
|
|
|
|
|
|
|
|
If the lookup_view is not an import path, it is assumed to be a URL pattern
|
|
|
|
label and the original string is returned.
|
|
|
|
|
|
|
|
If can_fail is True, lookup_view might be a URL pattern label, so errors
|
|
|
|
during the import fail and the string is returned.
|
|
|
|
"""
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
try:
|
|
|
|
# Bail out early if lookup_view is not ASCII. This can't be a function.
|
|
|
|
lookup_view = lookup_view.encode('ascii')
|
|
|
|
|
|
|
|
if not callable(lookup_view):
|
|
|
|
mod_name, func_name = get_mod_func(lookup_view)
|
|
|
|
try:
|
|
|
|
if func_name != '':
|
|
|
|
lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
|
|
|
|
except (ImportError, AttributeError):
|
|
|
|
if not can_fail:
|
|
|
|
raise
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
pass
|
2007-06-23 13:40:28 +08:00
|
|
|
return lookup_view
|
|
|
|
get_callable = memoize(get_callable, _callable_cache)
|
|
|
|
|
|
|
|
def get_resolver(urlconf):
|
|
|
|
if urlconf is None:
|
|
|
|
from django.conf import settings
|
|
|
|
urlconf = settings.ROOT_URLCONF
|
|
|
|
return RegexURLResolver(r'^/', urlconf)
|
|
|
|
get_resolver = memoize(get_resolver, _resolver_cache)
|
|
|
|
|
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, ''
|
2005-07-13 09:25:57 +08:00
|
|
|
return callback[:dot], callback[dot+1:]
|
|
|
|
|
2006-06-02 12:38:16 +08:00
|
|
|
def reverse_helper(regex, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Does a "reverse" lookup -- returns the URL for the given args/kwargs.
|
|
|
|
The args/kwargs are applied to the given compiled regular expression.
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> reverse_helper(re.compile('^places/(\d+)/$'), 3)
|
|
|
|
'places/3/'
|
|
|
|
>>> reverse_helper(re.compile('^places/(?P<id>\d+)/$'), id=3)
|
|
|
|
'places/3/'
|
|
|
|
>>> reverse_helper(re.compile('^people/(?P<state>\w\w)/(\w+)/$'), 'adrian', state='il')
|
|
|
|
'people/il/adrian/'
|
|
|
|
|
|
|
|
Raises NoReverseMatch if the args/kwargs aren't valid for the regex.
|
|
|
|
"""
|
|
|
|
# TODO: Handle nested parenthesis in the following regex.
|
|
|
|
result = re.sub(r'\(([^)]+)\)', MatchChecker(args, kwargs), regex.pattern)
|
|
|
|
return result.replace('^', '').replace('$', '')
|
|
|
|
|
2006-05-16 12:05:55 +08:00
|
|
|
class MatchChecker(object):
|
|
|
|
"Class used in reverse RegexURLPattern lookup."
|
|
|
|
def __init__(self, args, kwargs):
|
|
|
|
self.args, self.kwargs = args, kwargs
|
|
|
|
self.current_arg = 0
|
|
|
|
|
|
|
|
def __call__(self, match_obj):
|
|
|
|
# match_obj.group(1) is the contents of the parenthesis.
|
|
|
|
# First we need to figure out whether it's a named or unnamed group.
|
|
|
|
#
|
|
|
|
grouped = match_obj.group(1)
|
|
|
|
m = re.search(r'^\?P<(\w+)>(.*?)$', grouped)
|
|
|
|
if m: # If this was a named group...
|
|
|
|
# m.group(1) is the name of the group
|
|
|
|
# m.group(2) is the regex.
|
|
|
|
try:
|
|
|
|
value = self.kwargs[m.group(1)]
|
|
|
|
except KeyError:
|
|
|
|
# It was a named group, but the arg was passed in as a
|
|
|
|
# positional arg or not at all.
|
|
|
|
try:
|
|
|
|
value = self.args[self.current_arg]
|
|
|
|
self.current_arg += 1
|
|
|
|
except IndexError:
|
|
|
|
# The arg wasn't passed in.
|
|
|
|
raise NoReverseMatch('Not enough positional arguments passed in')
|
|
|
|
test_regex = m.group(2)
|
|
|
|
else: # Otherwise, this was a positional (unnamed) group.
|
|
|
|
try:
|
|
|
|
value = self.args[self.current_arg]
|
|
|
|
self.current_arg += 1
|
|
|
|
except IndexError:
|
|
|
|
# The arg wasn't passed in.
|
|
|
|
raise NoReverseMatch('Not enough positional arguments passed in')
|
|
|
|
test_regex = grouped
|
|
|
|
# Note we're using re.match here on purpose because the start of
|
|
|
|
# to string needs to match.
|
|
|
|
if not re.match(test_regex + '$', str(value)): # TODO: Unicode?
|
|
|
|
raise NoReverseMatch("Value %r didn't match regular expression %r" % (value, test_regex))
|
|
|
|
return str(value) # TODO: Unicode?
|
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class RegexURLPattern(object):
|
2007-04-01 15:25:20 +08:00
|
|
|
def __init__(self, regex, callback, default_args=None, name=None):
|
2005-08-06 04:50:19 +08:00
|
|
|
# regex is a string representing a regular expression.
|
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).
|
2005-08-06 04:50:19 +08:00
|
|
|
self.regex = re.compile(regex)
|
2006-08-11 15:01:29 +08:00
|
|
|
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-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)
|
|
|
|
|
2006-08-11 15:01:29 +08:00
|
|
|
return self.callback, args, kwargs
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-08-11 15:01:29 +08:00
|
|
|
def _get_callback(self):
|
|
|
|
if self._callback is not None:
|
|
|
|
return self._callback
|
2005-07-13 09:25:57 +08:00
|
|
|
try:
|
2007-06-23 13:40:28 +08:00
|
|
|
self._callback = get_callable(self._callback_str)
|
2005-08-01 22:41:01 +08:00
|
|
|
except ImportError, e:
|
2007-06-24 17:38:30 +08:00
|
|
|
mod_name, _ = get_mod_func(self._callback_str)
|
2005-08-01 22:41:01 +08:00
|
|
|
raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e))
|
|
|
|
except AttributeError, e:
|
2007-06-24 17:38:30 +08:00
|
|
|
mod_name, func_name = get_mod_func(self._callback_str)
|
2005-08-01 22:41:01 +08:00
|
|
|
raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
|
2006-08-11 15:01:29 +08:00
|
|
|
return self._callback
|
|
|
|
callback = property(_get_callback)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-16 12:05:55 +08:00
|
|
|
def reverse(self, viewname, *args, **kwargs):
|
2006-08-11 15:01:29 +08:00
|
|
|
mod_name, func_name = get_mod_func(viewname)
|
|
|
|
try:
|
2006-10-31 04:50:27 +08:00
|
|
|
lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
|
2006-08-11 15:01:29 +08:00
|
|
|
except (ImportError, AttributeError):
|
|
|
|
raise NoReverseMatch
|
|
|
|
if lookup_view != self.callback:
|
2006-05-16 12:05:55 +08:00
|
|
|
raise NoReverseMatch
|
|
|
|
return self.reverse_helper(*args, **kwargs)
|
|
|
|
|
|
|
|
def reverse_helper(self, *args, **kwargs):
|
2006-06-02 12:38:16 +08:00
|
|
|
return reverse_helper(self.regex, *args, **kwargs)
|
2006-05-16 12:05:55 +08:00
|
|
|
|
2005-08-11 06:20:18 +08:00
|
|
|
class RegexURLResolver(object):
|
2006-08-01 10:57:08 +08:00
|
|
|
def __init__(self, regex, urlconf_name, default_kwargs=None):
|
2005-08-06 04:50:19 +08:00
|
|
|
# regex is a string representing a regular expression.
|
|
|
|
# urlconf_name is a string representing the module containing urlconfs.
|
2005-07-13 09:25:57 +08:00
|
|
|
self.regex = re.compile(regex)
|
2005-08-06 04:50:19 +08:00
|
|
|
self.urlconf_name = 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 {}
|
2007-06-24 17:38:30 +08:00
|
|
|
self._reverse_dict = {}
|
|
|
|
|
|
|
|
def _get_reverse_dict(self):
|
2007-06-26 00:19:36 +08:00
|
|
|
if not self._reverse_dict and hasattr(self.urlconf_module, 'urlpatterns'):
|
2007-06-24 17:38:30 +08:00
|
|
|
for pattern in reversed(self.urlconf_module.urlpatterns):
|
|
|
|
if isinstance(pattern, RegexURLResolver):
|
|
|
|
for key, value in pattern.reverse_dict.iteritems():
|
|
|
|
self._reverse_dict[key] = (pattern,) + value
|
|
|
|
else:
|
|
|
|
self._reverse_dict[pattern.callback] = (pattern,)
|
|
|
|
self._reverse_dict[pattern.name] = (pattern,)
|
|
|
|
return self._reverse_dict
|
|
|
|
reverse_dict = property(_get_reverse_dict)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-08-06 04:50:19 +08:00
|
|
|
def resolve(self, path):
|
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():]
|
2005-08-11 06:20:18 +08:00
|
|
|
for pattern in self.urlconf_module.urlpatterns:
|
2005-08-06 06:22:41 +08:00
|
|
|
try:
|
|
|
|
sub_match = pattern.resolve(new_path)
|
|
|
|
except Resolver404, e:
|
|
|
|
tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']])
|
|
|
|
else:
|
|
|
|
if sub_match:
|
2006-08-01 10:57:08 +08:00
|
|
|
sub_match_dict = dict(self.default_kwargs, **sub_match[2])
|
|
|
|
return sub_match[0], sub_match[1], dict(match.groupdict(), **sub_match_dict)
|
2005-08-06 06:22:41 +08:00
|
|
|
tried.append(pattern.regex.pattern)
|
|
|
|
raise Resolver404, {'tried': tried, 'path': new_path}
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-08-06 04:50:19 +08:00
|
|
|
def _get_urlconf_module(self):
|
2005-08-11 06:20:18 +08:00
|
|
|
try:
|
|
|
|
return self._urlconf_module
|
|
|
|
except AttributeError:
|
2005-11-24 05:44:48 +08:00
|
|
|
try:
|
2006-10-31 04:50:27 +08:00
|
|
|
self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
|
2005-11-24 05:44:48 +08:00
|
|
|
except ValueError, e:
|
|
|
|
# Invalid urlconf_name, such as "foo.bar." (note trailing period)
|
|
|
|
raise ImproperlyConfigured, "Error while importing URLconf %r: %s" % (self.urlconf_name, e)
|
2005-08-11 06:20:18 +08:00
|
|
|
return self._urlconf_module
|
2005-08-06 04:50:19 +08:00
|
|
|
urlconf_module = property(_get_urlconf_module)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-09-29 21:29:12 +08:00
|
|
|
def _get_url_patterns(self):
|
2005-09-29 22:59:49 +08:00
|
|
|
return self.urlconf_module.urlpatterns
|
2005-09-29 21:29:12 +08:00
|
|
|
url_patterns = property(_get_url_patterns)
|
|
|
|
|
2005-08-06 04:50:19 +08:00
|
|
|
def _resolve_special(self, view_type):
|
|
|
|
callback = getattr(self.urlconf_module, 'handler%s' % view_type)
|
|
|
|
mod_name, func_name = get_mod_func(callback)
|
2005-07-13 09:25:57 +08:00
|
|
|
try:
|
2006-10-31 04:50:27 +08:00
|
|
|
return getattr(__import__(mod_name, {}, {}, ['']), func_name), {}
|
2005-07-19 12:30:23 +08:00
|
|
|
except (ImportError, AttributeError), e:
|
2005-08-06 04:50:19 +08:00
|
|
|
raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))
|
|
|
|
|
|
|
|
def resolve404(self):
|
|
|
|
return self._resolve_special('404')
|
|
|
|
|
|
|
|
def resolve500(self):
|
|
|
|
return self._resolve_special('500')
|
2006-05-16 12:05:55 +08:00
|
|
|
|
2006-08-11 15:01:29 +08:00
|
|
|
def reverse(self, lookup_view, *args, **kwargs):
|
2007-06-23 13:40:28 +08:00
|
|
|
try:
|
2007-06-25 12:34:34 +08:00
|
|
|
lookup_view = get_callable(lookup_view, True)
|
2007-06-23 13:40:28 +08:00
|
|
|
except (ImportError, AttributeError):
|
|
|
|
raise NoReverseMatch
|
|
|
|
if lookup_view in self.reverse_dict:
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
return u''.join([reverse_helper(part.regex, *args, **kwargs) for part in self.reverse_dict[lookup_view]])
|
2006-05-16 12:05:55 +08:00
|
|
|
raise NoReverseMatch
|
2006-06-02 12:38:16 +08:00
|
|
|
|
2006-08-11 15:01:29 +08:00
|
|
|
def reverse_helper(self, lookup_view, *args, **kwargs):
|
|
|
|
sub_match = self.reverse(lookup_view, *args, **kwargs)
|
2006-06-02 12:38:16 +08:00
|
|
|
result = reverse_helper(self.regex, *args, **kwargs)
|
|
|
|
return result + sub_match
|
2006-07-25 15:30:22 +08:00
|
|
|
|
|
|
|
def resolve(path, urlconf=None):
|
2007-06-23 13:40:28 +08:00
|
|
|
return get_resolver(urlconf).resolve(path)
|
2006-07-25 15:30:22 +08:00
|
|
|
|
2006-07-28 10:08:17 +08:00
|
|
|
def reverse(viewname, urlconf=None, args=None, kwargs=None):
|
2006-07-25 15:30:22 +08:00
|
|
|
args = args or []
|
|
|
|
kwargs = kwargs or {}
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname, *args, **kwargs))
|
2007-06-23 13:40:28 +08:00
|
|
|
|