2015-12-30 23:51:16 +08:00
|
|
|
"""
|
|
|
|
This module converts requested URLs to callback view functions.
|
|
|
|
|
2017-11-08 21:43:39 +08:00
|
|
|
URLResolver is the main class here. Its resolve() method takes a URL (as
|
2015-12-30 23:51:16 +08:00
|
|
|
a string) and returns a ResolverMatch object which provides access to all
|
|
|
|
attributes of the resolved URL match.
|
|
|
|
"""
|
|
|
|
import functools
|
2018-09-07 15:33:19 +08:00
|
|
|
import inspect
|
2015-12-30 23:51:16 +08:00
|
|
|
import re
|
2019-08-20 17:53:10 +08:00
|
|
|
import string
|
2015-12-30 23:51:16 +08:00
|
|
|
from importlib import import_module
|
2021-07-29 13:04:56 +08:00
|
|
|
from pickle import PicklingError
|
2017-01-26 21:25:15 +08:00
|
|
|
from urllib.parse import quote
|
2015-12-30 23:51:16 +08:00
|
|
|
|
2019-04-12 21:15:18 +08:00
|
|
|
from asgiref.local import Local
|
|
|
|
|
2016-03-06 03:20:40 +08:00
|
|
|
from django.conf import settings
|
2018-09-07 15:33:19 +08:00
|
|
|
from django.core.checks import Error, Warning
|
2016-10-06 03:34:26 +08:00
|
|
|
from django.core.checks.urls import check_resolver
|
2019-04-04 07:17:25 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.utils.datastructures import MultiValueDict
|
|
|
|
from django.utils.functional import cached_property
|
2018-07-25 04:18:17 +08:00
|
|
|
from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes
|
2019-10-26 22:42:32 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile, normalize
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.utils.translation import get_language
|
|
|
|
|
2016-10-21 01:29:04 +08:00
|
|
|
from .converters import get_converter
|
2015-12-30 23:51:16 +08:00
|
|
|
from .exceptions import NoReverseMatch, Resolver404
|
|
|
|
from .utils import get_callable
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class ResolverMatch:
|
2020-07-08 07:23:54 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
func,
|
|
|
|
args,
|
|
|
|
kwargs,
|
|
|
|
url_name=None,
|
|
|
|
app_names=None,
|
|
|
|
namespaces=None,
|
|
|
|
route=None,
|
|
|
|
tried=None,
|
|
|
|
):
|
2015-12-30 23:51:16 +08:00
|
|
|
self.func = func
|
|
|
|
self.args = args
|
|
|
|
self.kwargs = kwargs
|
|
|
|
self.url_name = url_name
|
2017-11-03 00:35:41 +08:00
|
|
|
self.route = route
|
2020-07-08 07:23:54 +08:00
|
|
|
self.tried = tried
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
# If a URLRegexResolver doesn't have a namespace or app_name, it passes
|
|
|
|
# in an empty value.
|
|
|
|
self.app_names = [x for x in app_names if x] if app_names else []
|
|
|
|
self.app_name = ":".join(self.app_names)
|
|
|
|
self.namespaces = [x for x in namespaces if x] if namespaces else []
|
|
|
|
self.namespace = ":".join(self.namespaces)
|
|
|
|
|
2022-01-10 21:01:35 +08:00
|
|
|
if hasattr(func, "view_class"):
|
|
|
|
func = func.view_class
|
2015-12-30 23:51:16 +08:00
|
|
|
if not hasattr(func, "__name__"):
|
|
|
|
# A class-based view
|
2017-05-21 05:16:36 +08:00
|
|
|
self._func_path = func.__class__.__module__ + "." + func.__class__.__name__
|
2015-12-30 23:51:16 +08:00
|
|
|
else:
|
|
|
|
# A function-based view
|
2017-05-21 05:16:36 +08:00
|
|
|
self._func_path = func.__module__ + "." + func.__name__
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
view_path = url_name or self._func_path
|
|
|
|
self.view_name = ":".join(self.namespaces + [view_path])
|
|
|
|
|
|
|
|
def __getitem__(self, index):
|
|
|
|
return (self.func, self.args, self.kwargs)[index]
|
|
|
|
|
|
|
|
def __repr__(self):
|
2021-03-19 22:44:03 +08:00
|
|
|
if isinstance(self.func, functools.partial):
|
|
|
|
func = repr(self.func)
|
|
|
|
else:
|
|
|
|
func = self._func_path
|
|
|
|
return (
|
|
|
|
"ResolverMatch(func=%s, args=%r, kwargs=%r, url_name=%r, "
|
|
|
|
"app_names=%r, namespaces=%r, route=%r)"
|
|
|
|
% (
|
|
|
|
func,
|
|
|
|
self.args,
|
|
|
|
self.kwargs,
|
|
|
|
self.url_name,
|
|
|
|
self.app_names,
|
|
|
|
self.namespaces,
|
|
|
|
self.route,
|
|
|
|
)
|
2015-12-30 23:51:16 +08:00
|
|
|
)
|
|
|
|
|
2021-07-29 13:04:56 +08:00
|
|
|
def __reduce_ex__(self, protocol):
|
|
|
|
raise PicklingError(f"Cannot pickle {self.__class__.__qualname__}.")
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
def get_resolver(urlconf=None):
|
|
|
|
if urlconf is None:
|
|
|
|
urlconf = settings.ROOT_URLCONF
|
2019-05-07 04:53:40 +08:00
|
|
|
return _get_cached_resolver(urlconf)
|
|
|
|
|
|
|
|
|
|
|
|
@functools.lru_cache(maxsize=None)
|
|
|
|
def _get_cached_resolver(urlconf=None):
|
2016-10-21 01:29:04 +08:00
|
|
|
return URLResolver(RegexPattern(r"^/"), urlconf)
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache(maxsize=None)
|
2018-05-27 04:56:17 +08:00
|
|
|
def get_ns_resolver(ns_pattern, resolver, converters):
|
2015-12-30 23:51:16 +08:00
|
|
|
# Build a namespaced resolver for the given parent URLconf pattern.
|
|
|
|
# This makes it possible to have captured parameters in the parent
|
|
|
|
# URLconf pattern.
|
2018-05-27 04:56:17 +08:00
|
|
|
pattern = RegexPattern(ns_pattern)
|
|
|
|
pattern.converters = dict(converters)
|
|
|
|
ns_resolver = URLResolver(pattern, resolver.url_patterns)
|
2016-10-21 01:29:04 +08:00
|
|
|
return URLResolver(RegexPattern(r"^/"), [ns_resolver])
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class LocaleRegexDescriptor:
|
2016-10-21 01:29:04 +08:00
|
|
|
def __init__(self, attr):
|
|
|
|
self.attr = attr
|
|
|
|
|
2016-11-06 20:52:07 +08:00
|
|
|
def __get__(self, instance, cls=None):
|
|
|
|
"""
|
|
|
|
Return a compiled regular expression based on the active language.
|
|
|
|
"""
|
|
|
|
if instance is None:
|
|
|
|
return self
|
|
|
|
# As a performance optimization, if the given regex string is a regular
|
|
|
|
# string (not a lazily-translated string proxy), compile it once and
|
|
|
|
# avoid per-language compilation.
|
2016-10-21 01:29:04 +08:00
|
|
|
pattern = getattr(instance, self.attr)
|
|
|
|
if isinstance(pattern, str):
|
|
|
|
instance.__dict__["regex"] = instance._compile(pattern)
|
2016-11-06 20:52:07 +08:00
|
|
|
return instance.__dict__["regex"]
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in instance._regex_dict:
|
2016-10-21 01:29:04 +08:00
|
|
|
instance._regex_dict[language_code] = instance._compile(str(pattern))
|
2016-11-06 20:52:07 +08:00
|
|
|
return instance._regex_dict[language_code]
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
|
2016-10-21 01:29:04 +08:00
|
|
|
class CheckURLMixin:
|
2016-10-06 03:34:26 +08:00
|
|
|
def describe(self):
|
|
|
|
"""
|
|
|
|
Format the URL pattern for display in warning messages.
|
|
|
|
"""
|
2016-10-21 01:29:04 +08:00
|
|
|
description = "'{}'".format(self)
|
|
|
|
if self.name:
|
2016-10-06 03:34:26 +08:00
|
|
|
description += " [name='{}']".format(self.name)
|
|
|
|
return description
|
|
|
|
|
|
|
|
def _check_pattern_startswith_slash(self):
|
|
|
|
"""
|
|
|
|
Check that the pattern does not begin with a forward slash.
|
|
|
|
"""
|
|
|
|
regex_pattern = self.regex.pattern
|
|
|
|
if not settings.APPEND_SLASH:
|
|
|
|
# Skip check as it can be useful to start a URL pattern with a slash
|
|
|
|
# when APPEND_SLASH=False.
|
|
|
|
return []
|
2017-10-01 08:33:07 +08:00
|
|
|
if regex_pattern.startswith(("/", "^/", "^\\/")) and not regex_pattern.endswith(
|
2022-02-08 19:09:55 +08:00
|
|
|
"/"
|
2017-10-01 08:33:07 +08:00
|
|
|
):
|
2016-10-06 03:34:26 +08:00
|
|
|
warning = Warning(
|
2016-10-21 01:29:04 +08:00
|
|
|
"Your URL pattern {} has a route beginning with a '/'. Remove this "
|
2016-10-06 03:34:26 +08:00
|
|
|
"slash as it is unnecessary. If this pattern is targeted in an "
|
|
|
|
"include(), ensure the include() pattern has a trailing '/'.".format(
|
|
|
|
self.describe()
|
|
|
|
),
|
|
|
|
id="urls.W002",
|
|
|
|
)
|
|
|
|
return [warning]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
|
2016-10-21 01:29:04 +08:00
|
|
|
class RegexPattern(CheckURLMixin):
|
|
|
|
regex = LocaleRegexDescriptor("_regex")
|
|
|
|
|
|
|
|
def __init__(self, regex, name=None, is_endpoint=False):
|
|
|
|
self._regex = regex
|
|
|
|
self._regex_dict = {}
|
|
|
|
self._is_endpoint = is_endpoint
|
|
|
|
self.name = name
|
|
|
|
self.converters = {}
|
|
|
|
|
|
|
|
def match(self, path):
|
2021-11-29 18:52:03 +08:00
|
|
|
match = (
|
|
|
|
self.regex.fullmatch(path)
|
|
|
|
if self._is_endpoint and self.regex.pattern.endswith("$")
|
|
|
|
else self.regex.search(path)
|
|
|
|
)
|
2016-10-21 01:29:04 +08:00
|
|
|
if match:
|
|
|
|
# If there are any named groups, use those as kwargs, ignoring
|
|
|
|
# non-named groups. Otherwise, pass all non-named arguments as
|
|
|
|
# positional arguments.
|
2019-12-06 16:32:51 +08:00
|
|
|
kwargs = match.groupdict()
|
2016-10-21 01:29:04 +08:00
|
|
|
args = () if kwargs else match.groups()
|
2019-12-06 16:32:51 +08:00
|
|
|
kwargs = {k: v for k, v in kwargs.items() if v is not None}
|
2016-10-21 01:29:04 +08:00
|
|
|
return path[match.end() :], args, kwargs
|
|
|
|
return None
|
|
|
|
|
|
|
|
def check(self):
|
|
|
|
warnings = []
|
|
|
|
warnings.extend(self._check_pattern_startswith_slash())
|
|
|
|
if not self._is_endpoint:
|
|
|
|
warnings.extend(self._check_include_trailing_dollar())
|
|
|
|
return warnings
|
|
|
|
|
|
|
|
def _check_include_trailing_dollar(self):
|
|
|
|
regex_pattern = self.regex.pattern
|
|
|
|
if regex_pattern.endswith("$") and not regex_pattern.endswith(r"\$"):
|
|
|
|
return [
|
|
|
|
Warning(
|
|
|
|
"Your URL pattern {} uses include with a route ending with a '$'. "
|
|
|
|
"Remove the dollar from the route to avoid problems including "
|
|
|
|
"URLs.".format(self.describe()),
|
|
|
|
id="urls.W001",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
|
|
|
def _compile(self, regex):
|
|
|
|
"""Compile and return the given regular expression."""
|
|
|
|
try:
|
|
|
|
return re.compile(regex)
|
|
|
|
except re.error as e:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
'"%s" is not a valid regular expression: %s' % (regex, e)
|
2019-12-31 04:29:01 +08:00
|
|
|
) from e
|
2016-10-21 01:29:04 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
2017-12-20 06:50:23 +08:00
|
|
|
return str(self._regex)
|
2016-10-21 01:29:04 +08:00
|
|
|
|
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
_PATH_PARAMETER_COMPONENT_RE = _lazy_re_compile(
|
2020-04-13 16:07:28 +08:00
|
|
|
r"<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>"
|
2016-10-21 01:29:04 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def _route_to_regex(route, is_endpoint=False):
|
|
|
|
"""
|
|
|
|
Convert a path pattern into a regular expression. Return the regular
|
|
|
|
expression and a dictionary mapping the capture names to the converters.
|
|
|
|
For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
|
|
|
|
and {'pk': <django.urls.converters.IntConverter>}.
|
|
|
|
"""
|
|
|
|
original_route = route
|
|
|
|
parts = ["^"]
|
|
|
|
converters = {}
|
|
|
|
while True:
|
|
|
|
match = _PATH_PARAMETER_COMPONENT_RE.search(route)
|
|
|
|
if not match:
|
|
|
|
parts.append(re.escape(route))
|
|
|
|
break
|
2020-08-30 03:17:58 +08:00
|
|
|
elif not set(match.group()).isdisjoint(string.whitespace):
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"URL route '%s' cannot contain whitespace in angle brackets "
|
|
|
|
"<…>." % original_route
|
|
|
|
)
|
2016-10-21 01:29:04 +08:00
|
|
|
parts.append(re.escape(route[: match.start()]))
|
|
|
|
route = route[match.end() :]
|
2020-05-11 04:03:39 +08:00
|
|
|
parameter = match["parameter"]
|
2016-10-21 01:29:04 +08:00
|
|
|
if not parameter.isidentifier():
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"URL route '%s' uses parameter name %r which isn't a valid "
|
|
|
|
"Python identifier." % (original_route, parameter)
|
|
|
|
)
|
2020-05-11 04:03:39 +08:00
|
|
|
raw_converter = match["converter"]
|
2016-10-21 01:29:04 +08:00
|
|
|
if raw_converter is None:
|
|
|
|
# If a converter isn't specified, the default is `str`.
|
|
|
|
raw_converter = "str"
|
|
|
|
try:
|
|
|
|
converter = get_converter(raw_converter)
|
|
|
|
except KeyError as e:
|
|
|
|
raise ImproperlyConfigured(
|
2019-12-31 04:29:01 +08:00
|
|
|
"URL route %r uses invalid converter %r."
|
|
|
|
% (original_route, raw_converter)
|
|
|
|
) from e
|
2016-10-21 01:29:04 +08:00
|
|
|
converters[parameter] = converter
|
|
|
|
parts.append("(?P<" + parameter + ">" + converter.regex + ")")
|
|
|
|
if is_endpoint:
|
2021-11-29 18:52:03 +08:00
|
|
|
parts.append(r"\Z")
|
2016-10-21 01:29:04 +08:00
|
|
|
return "".join(parts), converters
|
|
|
|
|
|
|
|
|
|
|
|
class RoutePattern(CheckURLMixin):
|
|
|
|
regex = LocaleRegexDescriptor("_route")
|
|
|
|
|
|
|
|
def __init__(self, route, name=None, is_endpoint=False):
|
|
|
|
self._route = route
|
|
|
|
self._regex_dict = {}
|
|
|
|
self._is_endpoint = is_endpoint
|
|
|
|
self.name = name
|
|
|
|
self.converters = _route_to_regex(str(route), is_endpoint)[1]
|
|
|
|
|
|
|
|
def match(self, path):
|
|
|
|
match = self.regex.search(path)
|
|
|
|
if match:
|
|
|
|
# RoutePattern doesn't allow non-named groups so args are ignored.
|
|
|
|
kwargs = match.groupdict()
|
|
|
|
for key, value in kwargs.items():
|
|
|
|
converter = self.converters[key]
|
|
|
|
try:
|
|
|
|
kwargs[key] = converter.to_python(value)
|
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
return path[match.end() :], (), kwargs
|
|
|
|
return None
|
|
|
|
|
|
|
|
def check(self):
|
2017-11-08 00:39:59 +08:00
|
|
|
warnings = self._check_pattern_startswith_slash()
|
|
|
|
route = self._route
|
|
|
|
if "(?P<" in route or route.startswith("^") or route.endswith("$"):
|
|
|
|
warnings.append(
|
|
|
|
Warning(
|
|
|
|
"Your URL pattern {} has a route that contains '(?P<', begins "
|
|
|
|
"with a '^', or ends with a '$'. This was likely an oversight "
|
|
|
|
"when migrating to django.urls.path().".format(self.describe()),
|
|
|
|
id="2_0.W001",
|
2022-02-08 19:09:55 +08:00
|
|
|
)
|
2017-11-08 00:39:59 +08:00
|
|
|
)
|
|
|
|
return warnings
|
2016-10-21 01:29:04 +08:00
|
|
|
|
|
|
|
def _compile(self, route):
|
|
|
|
return re.compile(_route_to_regex(route, self._is_endpoint)[0])
|
|
|
|
|
|
|
|
def __str__(self):
|
2017-12-20 06:50:23 +08:00
|
|
|
return str(self._route)
|
2016-10-21 01:29:04 +08:00
|
|
|
|
|
|
|
|
|
|
|
class LocalePrefixPattern:
|
|
|
|
def __init__(self, prefix_default_language=True):
|
|
|
|
self.prefix_default_language = prefix_default_language
|
|
|
|
self.converters = {}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def regex(self):
|
|
|
|
# This is only used by reverse() and cached in _reverse_dict.
|
|
|
|
return re.compile(self.language_prefix)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def language_prefix(self):
|
|
|
|
language_code = get_language() or settings.LANGUAGE_CODE
|
|
|
|
if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
|
|
|
|
return ""
|
|
|
|
else:
|
|
|
|
return "%s/" % language_code
|
|
|
|
|
|
|
|
def match(self, path):
|
|
|
|
language_prefix = self.language_prefix
|
|
|
|
if path.startswith(language_prefix):
|
|
|
|
return path[len(language_prefix) :], (), {}
|
|
|
|
return None
|
|
|
|
|
|
|
|
def check(self):
|
|
|
|
return []
|
|
|
|
|
|
|
|
def describe(self):
|
|
|
|
return "'{}'".format(self)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.language_prefix
|
|
|
|
|
|
|
|
|
|
|
|
class URLPattern:
|
|
|
|
def __init__(self, pattern, callback, default_args=None, name=None):
|
|
|
|
self.pattern = pattern
|
2015-12-30 23:51:16 +08:00
|
|
|
self.callback = callback # the view
|
|
|
|
self.default_args = default_args or {}
|
|
|
|
self.name = name
|
|
|
|
|
|
|
|
def __repr__(self):
|
2016-10-21 01:29:04 +08:00
|
|
|
return "<%s %s>" % (self.__class__.__name__, self.pattern.describe())
|
2015-12-30 23:51:16 +08:00
|
|
|
|
2016-10-06 03:34:26 +08:00
|
|
|
def check(self):
|
|
|
|
warnings = self._check_pattern_name()
|
2016-10-21 01:29:04 +08:00
|
|
|
warnings.extend(self.pattern.check())
|
2020-11-15 01:25:57 +08:00
|
|
|
warnings.extend(self._check_callback())
|
2016-10-06 03:34:26 +08:00
|
|
|
return warnings
|
|
|
|
|
|
|
|
def _check_pattern_name(self):
|
|
|
|
"""
|
|
|
|
Check that the pattern name does not contain a colon.
|
|
|
|
"""
|
2016-10-21 01:29:04 +08:00
|
|
|
if self.pattern.name is not None and ":" in self.pattern.name:
|
2016-10-06 03:34:26 +08:00
|
|
|
warning = Warning(
|
|
|
|
"Your URL pattern {} has a name including a ':'. Remove the colon, to "
|
2016-10-21 01:29:04 +08:00
|
|
|
"avoid ambiguous namespace references.".format(self.pattern.describe()),
|
2016-10-06 03:34:26 +08:00
|
|
|
id="urls.W003",
|
|
|
|
)
|
|
|
|
return [warning]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2020-11-15 01:25:57 +08:00
|
|
|
def _check_callback(self):
|
|
|
|
from django.views import View
|
|
|
|
|
|
|
|
view = self.callback
|
|
|
|
if inspect.isclass(view) and issubclass(view, View):
|
|
|
|
return [
|
|
|
|
Error(
|
|
|
|
"Your URL pattern %s has an invalid view, pass %s.as_view() "
|
|
|
|
"instead of %s."
|
|
|
|
% (
|
|
|
|
self.pattern.describe(),
|
|
|
|
view.__name__,
|
|
|
|
view.__name__,
|
|
|
|
),
|
|
|
|
id="urls.E009",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
def resolve(self, path):
|
2016-10-21 01:29:04 +08:00
|
|
|
match = self.pattern.match(path)
|
2015-12-30 23:51:16 +08:00
|
|
|
if match:
|
2016-10-21 01:29:04 +08:00
|
|
|
new_path, args, kwargs = match
|
|
|
|
# Pass any extra_kwargs as **kwargs.
|
2015-12-30 23:51:16 +08:00
|
|
|
kwargs.update(self.default_args)
|
2017-11-03 00:35:41 +08:00
|
|
|
return ResolverMatch(
|
|
|
|
self.callback, args, kwargs, self.pattern.name, route=str(self.pattern)
|
2022-02-08 19:09:55 +08:00
|
|
|
)
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def lookup_str(self):
|
|
|
|
"""
|
|
|
|
A string that identifies the view (e.g. 'path.to.view_function' or
|
|
|
|
'path.to.ClassBasedView').
|
|
|
|
"""
|
|
|
|
callback = self.callback
|
2017-02-18 08:45:34 +08:00
|
|
|
if isinstance(callback, functools.partial):
|
2015-12-30 23:51:16 +08:00
|
|
|
callback = callback.func
|
2021-03-17 18:55:00 +08:00
|
|
|
if hasattr(callback, "view_class"):
|
|
|
|
callback = callback.view_class
|
|
|
|
elif not hasattr(callback, "__name__"):
|
2015-12-30 23:51:16 +08:00
|
|
|
return callback.__module__ + "." + callback.__class__.__name__
|
2016-12-01 18:38:01 +08:00
|
|
|
return callback.__module__ + "." + callback.__qualname__
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
|
2016-10-21 01:29:04 +08:00
|
|
|
class URLResolver:
|
|
|
|
def __init__(
|
|
|
|
self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None
|
|
|
|
):
|
|
|
|
self.pattern = pattern
|
2015-12-30 23:51:16 +08:00
|
|
|
# urlconf_name is the dotted Python path to the module defining
|
|
|
|
# urlpatterns. It may also be an object with an urlpatterns attribute
|
|
|
|
# or urlpatterns itself.
|
|
|
|
self.urlconf_name = urlconf_name
|
|
|
|
self.callback = None
|
|
|
|
self.default_kwargs = default_kwargs or {}
|
|
|
|
self.namespace = namespace
|
|
|
|
self.app_name = app_name
|
|
|
|
self._reverse_dict = {}
|
|
|
|
self._namespace_dict = {}
|
|
|
|
self._app_dict = {}
|
|
|
|
# set of dotted paths to all functions and classes that are used in
|
|
|
|
# urlpatterns
|
|
|
|
self._callback_strs = set()
|
|
|
|
self._populated = False
|
2019-04-12 21:15:18 +08:00
|
|
|
self._local = Local()
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2017-11-30 00:54:34 +08:00
|
|
|
if isinstance(self.urlconf_name, list) and self.urlconf_name:
|
2015-12-30 23:51:16 +08:00
|
|
|
# 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)
|
2017-01-20 17:20:53 +08:00
|
|
|
return "<%s %s (%s:%s) %s>" % (
|
2015-12-30 23:51:16 +08:00
|
|
|
self.__class__.__name__,
|
|
|
|
urlconf_repr,
|
|
|
|
self.app_name,
|
2016-10-21 01:29:04 +08:00
|
|
|
self.namespace,
|
|
|
|
self.pattern.describe(),
|
2015-12-30 23:51:16 +08:00
|
|
|
)
|
|
|
|
|
2016-10-06 03:34:26 +08:00
|
|
|
def check(self):
|
2018-09-07 15:33:19 +08:00
|
|
|
messages = []
|
2016-10-06 03:34:26 +08:00
|
|
|
for pattern in self.url_patterns:
|
2018-09-07 15:33:19 +08:00
|
|
|
messages.extend(check_resolver(pattern))
|
|
|
|
messages.extend(self._check_custom_error_handlers())
|
|
|
|
return messages or self.pattern.check()
|
|
|
|
|
|
|
|
def _check_custom_error_handlers(self):
|
|
|
|
messages = []
|
|
|
|
# All handlers take (request, exception) arguments except handler500
|
|
|
|
# which takes (request).
|
|
|
|
for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]:
|
2019-04-04 07:17:25 +08:00
|
|
|
try:
|
2020-06-23 03:28:56 +08:00
|
|
|
handler = self.resolve_error_handler(status_code)
|
2019-04-04 07:17:25 +08:00
|
|
|
except (ImportError, ViewDoesNotExist) as e:
|
|
|
|
path = getattr(self.urlconf_module, "handler%s" % status_code)
|
|
|
|
msg = (
|
|
|
|
"The custom handler{status_code} view '{path}' could not be "
|
|
|
|
"imported."
|
|
|
|
).format(status_code=status_code, path=path)
|
|
|
|
messages.append(Error(msg, hint=str(e), id="urls.E008"))
|
|
|
|
continue
|
2018-09-07 15:33:19 +08:00
|
|
|
signature = inspect.signature(handler)
|
|
|
|
args = [None] * num_parameters
|
|
|
|
try:
|
|
|
|
signature.bind(*args)
|
|
|
|
except TypeError:
|
|
|
|
msg = (
|
|
|
|
"The custom handler{status_code} view '{path}' does not "
|
|
|
|
"take the correct number of arguments ({args})."
|
|
|
|
).format(
|
|
|
|
status_code=status_code,
|
|
|
|
path=handler.__module__ + "." + handler.__qualname__,
|
|
|
|
args="request, exception" if num_parameters == 2 else "request",
|
|
|
|
)
|
|
|
|
messages.append(Error(msg, id="urls.E007"))
|
|
|
|
return messages
|
2016-10-06 03:34:26 +08:00
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
def _populate(self):
|
2016-07-15 02:41:52 +08:00
|
|
|
# Short-circuit if called recursively in this thread to prevent
|
|
|
|
# infinite recursion. Concurrent threads may call this at the same
|
|
|
|
# time and will need to continue, so set 'populating' on a
|
|
|
|
# thread-local variable.
|
|
|
|
if getattr(self._local, "populating", False):
|
2016-06-18 22:39:32 +08:00
|
|
|
return
|
2016-10-21 01:29:04 +08:00
|
|
|
try:
|
2017-09-22 20:43:00 +08:00
|
|
|
self._local.populating = True
|
|
|
|
lookups = MultiValueDict()
|
|
|
|
namespaces = {}
|
|
|
|
apps = {}
|
|
|
|
language_code = get_language()
|
2016-10-21 01:29:04 +08:00
|
|
|
for url_pattern in reversed(self.url_patterns):
|
|
|
|
p_pattern = url_pattern.pattern.regex.pattern
|
|
|
|
if p_pattern.startswith("^"):
|
|
|
|
p_pattern = p_pattern[1:]
|
|
|
|
if isinstance(url_pattern, URLPattern):
|
|
|
|
self._callback_strs.add(url_pattern.lookup_str)
|
|
|
|
bits = normalize(url_pattern.pattern.regex.pattern)
|
|
|
|
lookups.appendlist(
|
|
|
|
url_pattern.callback,
|
|
|
|
(
|
|
|
|
bits,
|
|
|
|
p_pattern,
|
|
|
|
url_pattern.default_args,
|
|
|
|
url_pattern.pattern.converters,
|
2022-02-08 19:09:55 +08:00
|
|
|
),
|
2016-10-21 01:29:04 +08:00
|
|
|
)
|
|
|
|
if url_pattern.name is not None:
|
|
|
|
lookups.appendlist(
|
|
|
|
url_pattern.name,
|
|
|
|
(
|
|
|
|
bits,
|
|
|
|
p_pattern,
|
|
|
|
url_pattern.default_args,
|
|
|
|
url_pattern.pattern.converters,
|
2022-02-08 19:09:55 +08:00
|
|
|
),
|
2016-10-21 01:29:04 +08:00
|
|
|
)
|
|
|
|
else: # url_pattern is a URLResolver.
|
|
|
|
url_pattern._populate()
|
|
|
|
if url_pattern.app_name:
|
|
|
|
apps.setdefault(url_pattern.app_name, []).append(
|
|
|
|
url_pattern.namespace
|
|
|
|
)
|
|
|
|
namespaces[url_pattern.namespace] = (p_pattern, url_pattern)
|
|
|
|
else:
|
|
|
|
for name in url_pattern.reverse_dict:
|
|
|
|
for (
|
|
|
|
matches,
|
|
|
|
pat,
|
|
|
|
defaults,
|
|
|
|
converters,
|
|
|
|
) in url_pattern.reverse_dict.getlist(name):
|
|
|
|
new_matches = normalize(p_pattern + pat)
|
|
|
|
lookups.appendlist(
|
|
|
|
name,
|
|
|
|
(
|
|
|
|
new_matches,
|
|
|
|
p_pattern + pat,
|
2017-12-11 20:08:45 +08:00
|
|
|
{**defaults, **url_pattern.default_kwargs},
|
2018-05-27 04:56:17 +08:00
|
|
|
{
|
|
|
|
**self.pattern.converters,
|
|
|
|
**url_pattern.pattern.converters,
|
|
|
|
**converters,
|
2022-02-08 19:09:55 +08:00
|
|
|
},
|
2016-10-21 01:29:04 +08:00
|
|
|
),
|
2015-12-30 23:51:16 +08:00
|
|
|
)
|
2016-10-21 01:29:04 +08:00
|
|
|
for namespace, (
|
|
|
|
prefix,
|
|
|
|
sub_pattern,
|
|
|
|
) in url_pattern.namespace_dict.items():
|
2018-09-21 02:24:36 +08:00
|
|
|
current_converters = url_pattern.pattern.converters
|
|
|
|
sub_pattern.pattern.converters.update(current_converters)
|
2016-10-21 01:29:04 +08:00
|
|
|
namespaces[namespace] = (p_pattern + prefix, sub_pattern)
|
|
|
|
for app_name, namespace_list in url_pattern.app_dict.items():
|
|
|
|
apps.setdefault(app_name, []).extend(namespace_list)
|
|
|
|
self._callback_strs.update(url_pattern._callback_strs)
|
|
|
|
self._namespace_dict[language_code] = namespaces
|
|
|
|
self._app_dict[language_code] = apps
|
|
|
|
self._reverse_dict[language_code] = lookups
|
|
|
|
self._populated = True
|
|
|
|
finally:
|
|
|
|
self._local.populating = False
|
2015-12-30 23:51:16 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def reverse_dict(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._reverse_dict:
|
|
|
|
self._populate()
|
|
|
|
return self._reverse_dict[language_code]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def namespace_dict(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._namespace_dict:
|
|
|
|
self._populate()
|
|
|
|
return self._namespace_dict[language_code]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def app_dict(self):
|
|
|
|
language_code = get_language()
|
|
|
|
if language_code not in self._app_dict:
|
|
|
|
self._populate()
|
|
|
|
return self._app_dict[language_code]
|
|
|
|
|
2020-07-08 07:23:54 +08:00
|
|
|
@staticmethod
|
|
|
|
def _extend_tried(tried, pattern, sub_tried=None):
|
|
|
|
if sub_tried is None:
|
|
|
|
tried.append([pattern])
|
|
|
|
else:
|
|
|
|
tried.extend([pattern, *t] for t in sub_tried)
|
|
|
|
|
2017-11-03 00:35:41 +08:00
|
|
|
@staticmethod
|
|
|
|
def _join_route(route1, route2):
|
|
|
|
"""Join two routes, without the starting ^ in the second route."""
|
|
|
|
if not route1:
|
|
|
|
return route2
|
|
|
|
if route2.startswith("^"):
|
|
|
|
route2 = route2[1:]
|
|
|
|
return route1 + route2
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
def _is_callback(self, name):
|
|
|
|
if not self._populated:
|
|
|
|
self._populate()
|
|
|
|
return name in self._callback_strs
|
|
|
|
|
|
|
|
def resolve(self, path):
|
2017-04-22 01:52:26 +08:00
|
|
|
path = str(path) # path may be a reverse_lazy object
|
2015-12-30 23:51:16 +08:00
|
|
|
tried = []
|
2016-10-21 01:29:04 +08:00
|
|
|
match = self.pattern.match(path)
|
2015-12-30 23:51:16 +08:00
|
|
|
if match:
|
2016-10-21 01:29:04 +08:00
|
|
|
new_path, args, kwargs = match
|
2015-12-30 23:51:16 +08:00
|
|
|
for pattern in self.url_patterns:
|
|
|
|
try:
|
|
|
|
sub_match = pattern.resolve(new_path)
|
|
|
|
except Resolver404 as e:
|
2020-07-08 07:23:54 +08:00
|
|
|
self._extend_tried(tried, pattern, e.args[0].get("tried"))
|
2015-12-30 23:51:16 +08:00
|
|
|
else:
|
|
|
|
if sub_match:
|
|
|
|
# Merge captured arguments in match with submatch
|
2017-12-11 20:08:45 +08:00
|
|
|
sub_match_dict = {**kwargs, **self.default_kwargs}
|
2016-10-21 01:29:04 +08:00
|
|
|
# Update the sub_match_dict with the kwargs from the sub_match.
|
2015-12-30 23:51:16 +08:00
|
|
|
sub_match_dict.update(sub_match.kwargs)
|
|
|
|
# If there are *any* named groups, ignore all non-named groups.
|
|
|
|
# Otherwise, pass all non-named arguments as positional
|
|
|
|
# arguments.
|
|
|
|
sub_match_args = sub_match.args
|
|
|
|
if not sub_match_dict:
|
2016-10-21 01:29:04 +08:00
|
|
|
sub_match_args = args + sub_match.args
|
2017-11-03 00:35:41 +08:00
|
|
|
current_route = (
|
2022-02-08 19:09:55 +08:00
|
|
|
""
|
2017-11-03 00:35:41 +08:00
|
|
|
if isinstance(pattern, URLPattern)
|
|
|
|
else str(pattern.pattern)
|
2022-02-08 19:09:55 +08:00
|
|
|
)
|
2020-07-08 07:23:54 +08:00
|
|
|
self._extend_tried(tried, pattern, sub_match.tried)
|
2015-12-30 23:51:16 +08:00
|
|
|
return ResolverMatch(
|
|
|
|
sub_match.func,
|
|
|
|
sub_match_args,
|
|
|
|
sub_match_dict,
|
|
|
|
sub_match.url_name,
|
|
|
|
[self.app_name] + sub_match.app_names,
|
|
|
|
[self.namespace] + sub_match.namespaces,
|
2017-11-03 00:35:41 +08:00
|
|
|
self._join_route(current_route, sub_match.route),
|
2020-07-08 07:23:54 +08:00
|
|
|
tried,
|
2015-12-30 23:51:16 +08:00
|
|
|
)
|
2021-01-11 14:49:01 +08:00
|
|
|
tried.append([pattern])
|
2015-12-30 23:51:16 +08:00
|
|
|
raise Resolver404({"tried": tried, "path": new_path})
|
|
|
|
raise Resolver404({"path": path})
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def urlconf_module(self):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(self.urlconf_name, str):
|
2015-12-30 23:51:16 +08:00
|
|
|
return import_module(self.urlconf_name)
|
|
|
|
else:
|
|
|
|
return self.urlconf_name
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def url_patterns(self):
|
|
|
|
# urlconf_module might be a valid set of patterns, so we default to it
|
|
|
|
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
|
|
|
|
try:
|
|
|
|
iter(patterns)
|
2019-12-31 04:29:01 +08:00
|
|
|
except TypeError as e:
|
2015-12-30 23:51:16 +08:00
|
|
|
msg = (
|
2021-05-27 03:06:47 +08:00
|
|
|
"The included URLconf '{name}' does not appear to have "
|
|
|
|
"any patterns in it. If you see the 'urlpatterns' variable "
|
|
|
|
"with valid patterns in the file then the issue is probably "
|
|
|
|
"caused by a circular import."
|
2015-12-30 23:51:16 +08:00
|
|
|
)
|
2019-12-31 04:29:01 +08:00
|
|
|
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
|
2015-12-30 23:51:16 +08:00
|
|
|
return patterns
|
|
|
|
|
|
|
|
def resolve_error_handler(self, view_type):
|
|
|
|
callback = getattr(self.urlconf_module, "handler%s" % view_type, None)
|
|
|
|
if not callback:
|
|
|
|
# No handler specified in file; use lazy import, since
|
|
|
|
# django.conf.urls imports this file.
|
|
|
|
from django.conf import urls
|
2022-02-08 19:09:55 +08:00
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
callback = getattr(urls, "handler%s" % view_type)
|
2020-06-23 03:28:56 +08:00
|
|
|
return get_callable(callback)
|
2015-12-30 23:51:16 +08:00
|
|
|
|
2016-06-21 01:24:51 +08:00
|
|
|
def reverse(self, lookup_view, *args, **kwargs):
|
|
|
|
return self._reverse_with_prefix(lookup_view, "", *args, **kwargs)
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
|
|
|
|
if args and kwargs:
|
|
|
|
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
|
|
|
|
|
|
|
|
if not self._populated:
|
|
|
|
self._populate()
|
|
|
|
|
|
|
|
possibilities = self.reverse_dict.getlist(lookup_view)
|
|
|
|
|
2016-10-21 01:29:04 +08:00
|
|
|
for possibility, pattern, defaults, converters in possibilities:
|
2015-12-30 23:51:16 +08:00
|
|
|
for result, params in possibility:
|
|
|
|
if args:
|
|
|
|
if len(args) != len(params):
|
|
|
|
continue
|
2016-10-21 01:29:04 +08:00
|
|
|
candidate_subs = dict(zip(params, args))
|
2015-12-30 23:51:16 +08:00
|
|
|
else:
|
2017-07-29 22:16:43 +08:00
|
|
|
if set(kwargs).symmetric_difference(params).difference(defaults):
|
2015-12-30 23:51:16 +08:00
|
|
|
continue
|
2017-12-27 02:44:12 +08:00
|
|
|
if any(kwargs.get(k, v) != v for k, v in defaults.items()):
|
2015-12-30 23:51:16 +08:00
|
|
|
continue
|
2016-10-21 01:29:04 +08:00
|
|
|
candidate_subs = kwargs
|
|
|
|
# Convert the candidate subs to text using Converter.to_url().
|
|
|
|
text_candidate_subs = {}
|
2019-12-22 02:22:18 +08:00
|
|
|
match = True
|
2016-10-21 01:29:04 +08:00
|
|
|
for k, v in candidate_subs.items():
|
|
|
|
if k in converters:
|
2019-12-22 02:22:18 +08:00
|
|
|
try:
|
|
|
|
text_candidate_subs[k] = converters[k].to_url(v)
|
|
|
|
except ValueError:
|
|
|
|
match = False
|
|
|
|
break
|
2016-10-21 01:29:04 +08:00
|
|
|
else:
|
|
|
|
text_candidate_subs[k] = str(v)
|
2019-12-22 02:22:18 +08:00
|
|
|
if not match:
|
|
|
|
continue
|
2015-12-30 23:51:16 +08:00
|
|
|
# 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.replace("%", "%%") + result
|
2016-10-21 01:29:04 +08:00
|
|
|
if re.search(
|
|
|
|
"^%s%s" % (re.escape(_prefix), pattern),
|
|
|
|
candidate_pat % text_candidate_subs,
|
|
|
|
):
|
2015-12-30 23:51:16 +08:00
|
|
|
# safe characters from `pchar` definition of RFC 3986
|
2016-10-21 01:29:04 +08:00
|
|
|
url = quote(
|
|
|
|
candidate_pat % text_candidate_subs,
|
|
|
|
safe=RFC3986_SUBDELIMS + "/~:@",
|
|
|
|
)
|
2015-12-30 23:51:16 +08:00
|
|
|
# Don't allow construction of scheme relative urls.
|
2018-07-25 04:18:17 +08:00
|
|
|
return escape_leading_slashes(url)
|
2015-12-30 23:51:16 +08:00
|
|
|
# lookup_view can be URL name or callable, 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
|
|
|
|
|
2016-10-21 01:29:04 +08:00
|
|
|
patterns = [pattern for (_, pattern, _, _) in possibilities]
|
2017-01-12 10:40:18 +08:00
|
|
|
if patterns:
|
|
|
|
if args:
|
|
|
|
arg_msg = "arguments '%s'" % (args,)
|
|
|
|
elif kwargs:
|
2020-04-25 21:53:30 +08:00
|
|
|
arg_msg = "keyword arguments '%s'" % kwargs
|
2017-01-12 10:40:18 +08:00
|
|
|
else:
|
|
|
|
arg_msg = "no arguments"
|
|
|
|
msg = "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % (
|
|
|
|
lookup_view_s,
|
|
|
|
arg_msg,
|
|
|
|
len(patterns),
|
|
|
|
patterns,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
msg = (
|
|
|
|
"Reverse for '%(view)s' not found. '%(view)s' is not "
|
|
|
|
"a valid view function or pattern name." % {"view": lookup_view_s}
|
|
|
|
)
|
|
|
|
raise NoReverseMatch(msg)
|