resolvers.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. """
  2. This module converts requested URLs to callback view functions.
  3. URLResolver is the main class here. Its resolve() method takes a URL (as
  4. a string) and returns a ResolverMatch object which provides access to all
  5. attributes of the resolved URL match.
  6. """
  7. import functools
  8. import inspect
  9. import re
  10. import string
  11. from importlib import import_module
  12. from pickle import PicklingError
  13. from urllib.parse import quote
  14. from asgiref.local import Local
  15. from django.conf import settings
  16. from django.core.checks import Error, Warning
  17. from django.core.checks.urls import check_resolver
  18. from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
  19. from django.utils.datastructures import MultiValueDict
  20. from django.utils.functional import cached_property
  21. from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes
  22. from django.utils.regex_helper import _lazy_re_compile, normalize
  23. from django.utils.translation import get_language
  24. from .converters import get_converter
  25. from .exceptions import NoReverseMatch, Resolver404
  26. from .utils import get_callable
  27. class ResolverMatch:
  28. def __init__(
  29. self,
  30. func,
  31. args,
  32. kwargs,
  33. url_name=None,
  34. app_names=None,
  35. namespaces=None,
  36. route=None,
  37. tried=None,
  38. captured_kwargs=None,
  39. extra_kwargs=None,
  40. ):
  41. self.func = func
  42. self.args = args
  43. self.kwargs = kwargs
  44. self.url_name = url_name
  45. self.route = route
  46. self.tried = tried
  47. self.captured_kwargs = captured_kwargs
  48. self.extra_kwargs = extra_kwargs
  49. # If a URLRegexResolver doesn't have a namespace or app_name, it passes
  50. # in an empty value.
  51. self.app_names = [x for x in app_names if x] if app_names else []
  52. self.app_name = ":".join(self.app_names)
  53. self.namespaces = [x for x in namespaces if x] if namespaces else []
  54. self.namespace = ":".join(self.namespaces)
  55. if hasattr(func, "view_class"):
  56. func = func.view_class
  57. if not hasattr(func, "__name__"):
  58. # A class-based view
  59. self._func_path = func.__class__.__module__ + "." + func.__class__.__name__
  60. else:
  61. # A function-based view
  62. self._func_path = func.__module__ + "." + func.__name__
  63. view_path = url_name or self._func_path
  64. self.view_name = ":".join(self.namespaces + [view_path])
  65. def __getitem__(self, index):
  66. return (self.func, self.args, self.kwargs)[index]
  67. def __repr__(self):
  68. if isinstance(self.func, functools.partial):
  69. func = repr(self.func)
  70. else:
  71. func = self._func_path
  72. return (
  73. "ResolverMatch(func=%s, args=%r, kwargs=%r, url_name=%r, "
  74. "app_names=%r, namespaces=%r, route=%r%s%s)"
  75. % (
  76. func,
  77. self.args,
  78. self.kwargs,
  79. self.url_name,
  80. self.app_names,
  81. self.namespaces,
  82. self.route,
  83. f", captured_kwargs={self.captured_kwargs!r}"
  84. if self.captured_kwargs
  85. else "",
  86. f", extra_kwargs={self.extra_kwargs!r}" if self.extra_kwargs else "",
  87. )
  88. )
  89. def __reduce_ex__(self, protocol):
  90. raise PicklingError(f"Cannot pickle {self.__class__.__qualname__}.")
  91. def get_resolver(urlconf=None):
  92. if urlconf is None:
  93. urlconf = settings.ROOT_URLCONF
  94. return _get_cached_resolver(urlconf)
  95. @functools.cache
  96. def _get_cached_resolver(urlconf=None):
  97. return URLResolver(RegexPattern(r"^/"), urlconf)
  98. @functools.cache
  99. def get_ns_resolver(ns_pattern, resolver, converters):
  100. # Build a namespaced resolver for the given parent URLconf pattern.
  101. # This makes it possible to have captured parameters in the parent
  102. # URLconf pattern.
  103. pattern = RegexPattern(ns_pattern)
  104. pattern.converters = dict(converters)
  105. ns_resolver = URLResolver(pattern, resolver.url_patterns)
  106. return URLResolver(RegexPattern(r"^/"), [ns_resolver])
  107. class LocaleRegexDescriptor:
  108. def __init__(self, attr):
  109. self.attr = attr
  110. def __get__(self, instance, cls=None):
  111. """
  112. Return a compiled regular expression based on the active language.
  113. """
  114. if instance is None:
  115. return self
  116. # As a performance optimization, if the given regex string is a regular
  117. # string (not a lazily-translated string proxy), compile it once and
  118. # avoid per-language compilation.
  119. pattern = getattr(instance, self.attr)
  120. if isinstance(pattern, str):
  121. instance.__dict__["regex"] = instance._compile(pattern)
  122. return instance.__dict__["regex"]
  123. language_code = get_language()
  124. if language_code not in instance._regex_dict:
  125. instance._regex_dict[language_code] = instance._compile(str(pattern))
  126. return instance._regex_dict[language_code]
  127. class CheckURLMixin:
  128. def describe(self):
  129. """
  130. Format the URL pattern for display in warning messages.
  131. """
  132. description = "'{}'".format(self)
  133. if self.name:
  134. description += " [name='{}']".format(self.name)
  135. return description
  136. def _check_pattern_startswith_slash(self):
  137. """
  138. Check that the pattern does not begin with a forward slash.
  139. """
  140. regex_pattern = self.regex.pattern
  141. if not settings.APPEND_SLASH:
  142. # Skip check as it can be useful to start a URL pattern with a slash
  143. # when APPEND_SLASH=False.
  144. return []
  145. if regex_pattern.startswith(("/", "^/", "^\\/")) and not regex_pattern.endswith(
  146. "/"
  147. ):
  148. warning = Warning(
  149. "Your URL pattern {} has a route beginning with a '/'. Remove this "
  150. "slash as it is unnecessary. If this pattern is targeted in an "
  151. "include(), ensure the include() pattern has a trailing '/'.".format(
  152. self.describe()
  153. ),
  154. id="urls.W002",
  155. )
  156. return [warning]
  157. else:
  158. return []
  159. class RegexPattern(CheckURLMixin):
  160. regex = LocaleRegexDescriptor("_regex")
  161. def __init__(self, regex, name=None, is_endpoint=False):
  162. self._regex = regex
  163. self._regex_dict = {}
  164. self._is_endpoint = is_endpoint
  165. self.name = name
  166. self.converters = {}
  167. def match(self, path):
  168. match = (
  169. self.regex.fullmatch(path)
  170. if self._is_endpoint and self.regex.pattern.endswith("$")
  171. else self.regex.search(path)
  172. )
  173. if match:
  174. # If there are any named groups, use those as kwargs, ignoring
  175. # non-named groups. Otherwise, pass all non-named arguments as
  176. # positional arguments.
  177. kwargs = match.groupdict()
  178. args = () if kwargs else match.groups()
  179. kwargs = {k: v for k, v in kwargs.items() if v is not None}
  180. return path[match.end() :], args, kwargs
  181. return None
  182. def check(self):
  183. warnings = []
  184. warnings.extend(self._check_pattern_startswith_slash())
  185. if not self._is_endpoint:
  186. warnings.extend(self._check_include_trailing_dollar())
  187. return warnings
  188. def _check_include_trailing_dollar(self):
  189. regex_pattern = self.regex.pattern
  190. if regex_pattern.endswith("$") and not regex_pattern.endswith(r"\$"):
  191. return [
  192. Warning(
  193. "Your URL pattern {} uses include with a route ending with a '$'. "
  194. "Remove the dollar from the route to avoid problems including "
  195. "URLs.".format(self.describe()),
  196. id="urls.W001",
  197. )
  198. ]
  199. else:
  200. return []
  201. def _compile(self, regex):
  202. """Compile and return the given regular expression."""
  203. try:
  204. return re.compile(regex)
  205. except re.error as e:
  206. raise ImproperlyConfigured(
  207. '"%s" is not a valid regular expression: %s' % (regex, e)
  208. ) from e
  209. def __str__(self):
  210. return str(self._regex)
  211. _PATH_PARAMETER_COMPONENT_RE = _lazy_re_compile(
  212. r"<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>"
  213. )
  214. def _route_to_regex(route, is_endpoint=False):
  215. """
  216. Convert a path pattern into a regular expression. Return the regular
  217. expression and a dictionary mapping the capture names to the converters.
  218. For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
  219. and {'pk': <django.urls.converters.IntConverter>}.
  220. """
  221. original_route = route
  222. parts = ["^"]
  223. converters = {}
  224. while True:
  225. match = _PATH_PARAMETER_COMPONENT_RE.search(route)
  226. if not match:
  227. parts.append(re.escape(route))
  228. break
  229. elif not set(match.group()).isdisjoint(string.whitespace):
  230. raise ImproperlyConfigured(
  231. "URL route '%s' cannot contain whitespace in angle brackets "
  232. "<…>." % original_route
  233. )
  234. parts.append(re.escape(route[: match.start()]))
  235. route = route[match.end() :]
  236. parameter = match["parameter"]
  237. if not parameter.isidentifier():
  238. raise ImproperlyConfigured(
  239. "URL route '%s' uses parameter name %r which isn't a valid "
  240. "Python identifier." % (original_route, parameter)
  241. )
  242. raw_converter = match["converter"]
  243. if raw_converter is None:
  244. # If a converter isn't specified, the default is `str`.
  245. raw_converter = "str"
  246. try:
  247. converter = get_converter(raw_converter)
  248. except KeyError as e:
  249. raise ImproperlyConfigured(
  250. "URL route %r uses invalid converter %r."
  251. % (original_route, raw_converter)
  252. ) from e
  253. converters[parameter] = converter
  254. parts.append("(?P<" + parameter + ">" + converter.regex + ")")
  255. if is_endpoint:
  256. parts.append(r"\Z")
  257. return "".join(parts), converters
  258. class RoutePattern(CheckURLMixin):
  259. regex = LocaleRegexDescriptor("_route")
  260. def __init__(self, route, name=None, is_endpoint=False):
  261. self._route = route
  262. self._regex_dict = {}
  263. self._is_endpoint = is_endpoint
  264. self.name = name
  265. self.converters = _route_to_regex(str(route), is_endpoint)[1]
  266. def match(self, path):
  267. match = self.regex.search(path)
  268. if match:
  269. # RoutePattern doesn't allow non-named groups so args are ignored.
  270. kwargs = match.groupdict()
  271. for key, value in kwargs.items():
  272. converter = self.converters[key]
  273. try:
  274. kwargs[key] = converter.to_python(value)
  275. except ValueError:
  276. return None
  277. return path[match.end() :], (), kwargs
  278. return None
  279. def check(self):
  280. warnings = [
  281. *self._check_pattern_startswith_slash(),
  282. *self._check_pattern_unmatched_angle_brackets(),
  283. ]
  284. route = self._route
  285. if "(?P<" in route or route.startswith("^") or route.endswith("$"):
  286. warnings.append(
  287. Warning(
  288. "Your URL pattern {} has a route that contains '(?P<', begins "
  289. "with a '^', or ends with a '$'. This was likely an oversight "
  290. "when migrating to django.urls.path().".format(self.describe()),
  291. id="2_0.W001",
  292. )
  293. )
  294. return warnings
  295. def _check_pattern_unmatched_angle_brackets(self):
  296. warnings = []
  297. msg = "Your URL pattern %s has an unmatched '%s' bracket."
  298. brackets = re.findall(r"[<>]", str(self._route))
  299. open_bracket_counter = 0
  300. for bracket in brackets:
  301. if bracket == "<":
  302. open_bracket_counter += 1
  303. elif bracket == ">":
  304. open_bracket_counter -= 1
  305. if open_bracket_counter < 0:
  306. warnings.append(
  307. Warning(msg % (self.describe(), ">"), id="urls.W010")
  308. )
  309. open_bracket_counter = 0
  310. if open_bracket_counter > 0:
  311. warnings.append(Warning(msg % (self.describe(), "<"), id="urls.W010"))
  312. return warnings
  313. def _compile(self, route):
  314. return re.compile(_route_to_regex(route, self._is_endpoint)[0])
  315. def __str__(self):
  316. return str(self._route)
  317. class LocalePrefixPattern:
  318. def __init__(self, prefix_default_language=True):
  319. self.prefix_default_language = prefix_default_language
  320. self.converters = {}
  321. @property
  322. def regex(self):
  323. # This is only used by reverse() and cached in _reverse_dict.
  324. return re.compile(re.escape(self.language_prefix))
  325. @property
  326. def language_prefix(self):
  327. language_code = get_language() or settings.LANGUAGE_CODE
  328. if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
  329. return ""
  330. else:
  331. return "%s/" % language_code
  332. def match(self, path):
  333. language_prefix = self.language_prefix
  334. if path.startswith(language_prefix):
  335. return path.removeprefix(language_prefix), (), {}
  336. return None
  337. def check(self):
  338. return []
  339. def describe(self):
  340. return "'{}'".format(self)
  341. def __str__(self):
  342. return self.language_prefix
  343. class URLPattern:
  344. def __init__(self, pattern, callback, default_args=None, name=None):
  345. self.pattern = pattern
  346. self.callback = callback # the view
  347. self.default_args = default_args or {}
  348. self.name = name
  349. def __repr__(self):
  350. return "<%s %s>" % (self.__class__.__name__, self.pattern.describe())
  351. def check(self):
  352. warnings = self._check_pattern_name()
  353. warnings.extend(self.pattern.check())
  354. warnings.extend(self._check_callback())
  355. return warnings
  356. def _check_pattern_name(self):
  357. """
  358. Check that the pattern name does not contain a colon.
  359. """
  360. if self.pattern.name is not None and ":" in self.pattern.name:
  361. warning = Warning(
  362. "Your URL pattern {} has a name including a ':'. Remove the colon, to "
  363. "avoid ambiguous namespace references.".format(self.pattern.describe()),
  364. id="urls.W003",
  365. )
  366. return [warning]
  367. else:
  368. return []
  369. def _check_callback(self):
  370. from django.views import View
  371. view = self.callback
  372. if inspect.isclass(view) and issubclass(view, View):
  373. return [
  374. Error(
  375. "Your URL pattern %s has an invalid view, pass %s.as_view() "
  376. "instead of %s."
  377. % (
  378. self.pattern.describe(),
  379. view.__name__,
  380. view.__name__,
  381. ),
  382. id="urls.E009",
  383. )
  384. ]
  385. return []
  386. def resolve(self, path):
  387. match = self.pattern.match(path)
  388. if match:
  389. new_path, args, captured_kwargs = match
  390. # Pass any default args as **kwargs.
  391. kwargs = {**captured_kwargs, **self.default_args}
  392. return ResolverMatch(
  393. self.callback,
  394. args,
  395. kwargs,
  396. self.pattern.name,
  397. route=str(self.pattern),
  398. captured_kwargs=captured_kwargs,
  399. extra_kwargs=self.default_args,
  400. )
  401. @cached_property
  402. def lookup_str(self):
  403. """
  404. A string that identifies the view (e.g. 'path.to.view_function' or
  405. 'path.to.ClassBasedView').
  406. """
  407. callback = self.callback
  408. if isinstance(callback, functools.partial):
  409. callback = callback.func
  410. if hasattr(callback, "view_class"):
  411. callback = callback.view_class
  412. elif not hasattr(callback, "__name__"):
  413. return callback.__module__ + "." + callback.__class__.__name__
  414. return callback.__module__ + "." + callback.__qualname__
  415. class URLResolver:
  416. def __init__(
  417. self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None
  418. ):
  419. self.pattern = pattern
  420. # urlconf_name is the dotted Python path to the module defining
  421. # urlpatterns. It may also be an object with an urlpatterns attribute
  422. # or urlpatterns itself.
  423. self.urlconf_name = urlconf_name
  424. self.callback = None
  425. self.default_kwargs = default_kwargs or {}
  426. self.namespace = namespace
  427. self.app_name = app_name
  428. self._reverse_dict = {}
  429. self._namespace_dict = {}
  430. self._app_dict = {}
  431. # set of dotted paths to all functions and classes that are used in
  432. # urlpatterns
  433. self._callback_strs = set()
  434. self._populated = False
  435. self._local = Local()
  436. def __repr__(self):
  437. if isinstance(self.urlconf_name, list) and self.urlconf_name:
  438. # Don't bother to output the whole list, it can be huge
  439. urlconf_repr = "<%s list>" % self.urlconf_name[0].__class__.__name__
  440. else:
  441. urlconf_repr = repr(self.urlconf_name)
  442. return "<%s %s (%s:%s) %s>" % (
  443. self.__class__.__name__,
  444. urlconf_repr,
  445. self.app_name,
  446. self.namespace,
  447. self.pattern.describe(),
  448. )
  449. def check(self):
  450. messages = []
  451. for pattern in self.url_patterns:
  452. messages.extend(check_resolver(pattern))
  453. messages.extend(self._check_custom_error_handlers())
  454. return messages or self.pattern.check()
  455. def _check_custom_error_handlers(self):
  456. messages = []
  457. # All handlers take (request, exception) arguments except handler500
  458. # which takes (request).
  459. for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]:
  460. try:
  461. handler = self.resolve_error_handler(status_code)
  462. except (ImportError, ViewDoesNotExist) as e:
  463. path = getattr(self.urlconf_module, "handler%s" % status_code)
  464. msg = (
  465. "The custom handler{status_code} view '{path}' could not be "
  466. "imported."
  467. ).format(status_code=status_code, path=path)
  468. messages.append(Error(msg, hint=str(e), id="urls.E008"))
  469. continue
  470. signature = inspect.signature(handler)
  471. args = [None] * num_parameters
  472. try:
  473. signature.bind(*args)
  474. except TypeError:
  475. msg = (
  476. "The custom handler{status_code} view '{path}' does not "
  477. "take the correct number of arguments ({args})."
  478. ).format(
  479. status_code=status_code,
  480. path=handler.__module__ + "." + handler.__qualname__,
  481. args="request, exception" if num_parameters == 2 else "request",
  482. )
  483. messages.append(Error(msg, id="urls.E007"))
  484. return messages
  485. def _populate(self):
  486. # Short-circuit if called recursively in this thread to prevent
  487. # infinite recursion. Concurrent threads may call this at the same
  488. # time and will need to continue, so set 'populating' on a
  489. # thread-local variable.
  490. if getattr(self._local, "populating", False):
  491. return
  492. try:
  493. self._local.populating = True
  494. lookups = MultiValueDict()
  495. namespaces = {}
  496. apps = {}
  497. language_code = get_language()
  498. for url_pattern in reversed(self.url_patterns):
  499. p_pattern = url_pattern.pattern.regex.pattern
  500. p_pattern = p_pattern.removeprefix("^")
  501. if isinstance(url_pattern, URLPattern):
  502. self._callback_strs.add(url_pattern.lookup_str)
  503. bits = normalize(url_pattern.pattern.regex.pattern)
  504. lookups.appendlist(
  505. url_pattern.callback,
  506. (
  507. bits,
  508. p_pattern,
  509. url_pattern.default_args,
  510. url_pattern.pattern.converters,
  511. ),
  512. )
  513. if url_pattern.name is not None:
  514. lookups.appendlist(
  515. url_pattern.name,
  516. (
  517. bits,
  518. p_pattern,
  519. url_pattern.default_args,
  520. url_pattern.pattern.converters,
  521. ),
  522. )
  523. else: # url_pattern is a URLResolver.
  524. url_pattern._populate()
  525. if url_pattern.app_name:
  526. apps.setdefault(url_pattern.app_name, []).append(
  527. url_pattern.namespace
  528. )
  529. namespaces[url_pattern.namespace] = (p_pattern, url_pattern)
  530. else:
  531. for name in url_pattern.reverse_dict:
  532. for (
  533. matches,
  534. pat,
  535. defaults,
  536. converters,
  537. ) in url_pattern.reverse_dict.getlist(name):
  538. new_matches = normalize(p_pattern + pat)
  539. lookups.appendlist(
  540. name,
  541. (
  542. new_matches,
  543. p_pattern + pat,
  544. {**defaults, **url_pattern.default_kwargs},
  545. {
  546. **self.pattern.converters,
  547. **url_pattern.pattern.converters,
  548. **converters,
  549. },
  550. ),
  551. )
  552. for namespace, (
  553. prefix,
  554. sub_pattern,
  555. ) in url_pattern.namespace_dict.items():
  556. current_converters = url_pattern.pattern.converters
  557. sub_pattern.pattern.converters.update(current_converters)
  558. namespaces[namespace] = (p_pattern + prefix, sub_pattern)
  559. for app_name, namespace_list in url_pattern.app_dict.items():
  560. apps.setdefault(app_name, []).extend(namespace_list)
  561. self._callback_strs.update(url_pattern._callback_strs)
  562. self._namespace_dict[language_code] = namespaces
  563. self._app_dict[language_code] = apps
  564. self._reverse_dict[language_code] = lookups
  565. self._populated = True
  566. finally:
  567. self._local.populating = False
  568. @property
  569. def reverse_dict(self):
  570. language_code = get_language()
  571. if language_code not in self._reverse_dict:
  572. self._populate()
  573. return self._reverse_dict[language_code]
  574. @property
  575. def namespace_dict(self):
  576. language_code = get_language()
  577. if language_code not in self._namespace_dict:
  578. self._populate()
  579. return self._namespace_dict[language_code]
  580. @property
  581. def app_dict(self):
  582. language_code = get_language()
  583. if language_code not in self._app_dict:
  584. self._populate()
  585. return self._app_dict[language_code]
  586. @staticmethod
  587. def _extend_tried(tried, pattern, sub_tried=None):
  588. if sub_tried is None:
  589. tried.append([pattern])
  590. else:
  591. tried.extend([pattern, *t] for t in sub_tried)
  592. @staticmethod
  593. def _join_route(route1, route2):
  594. """Join two routes, without the starting ^ in the second route."""
  595. if not route1:
  596. return route2
  597. route2 = route2.removeprefix("^")
  598. return route1 + route2
  599. def _is_callback(self, name):
  600. if not self._populated:
  601. self._populate()
  602. return name in self._callback_strs
  603. def resolve(self, path):
  604. path = str(path) # path may be a reverse_lazy object
  605. tried = []
  606. match = self.pattern.match(path)
  607. if match:
  608. new_path, args, kwargs = match
  609. for pattern in self.url_patterns:
  610. try:
  611. sub_match = pattern.resolve(new_path)
  612. except Resolver404 as e:
  613. self._extend_tried(tried, pattern, e.args[0].get("tried"))
  614. else:
  615. if sub_match:
  616. # Merge captured arguments in match with submatch
  617. sub_match_dict = {**kwargs, **self.default_kwargs}
  618. # Update the sub_match_dict with the kwargs from the sub_match.
  619. sub_match_dict.update(sub_match.kwargs)
  620. # If there are *any* named groups, ignore all non-named groups.
  621. # Otherwise, pass all non-named arguments as positional
  622. # arguments.
  623. sub_match_args = sub_match.args
  624. if not sub_match_dict:
  625. sub_match_args = args + sub_match.args
  626. current_route = (
  627. ""
  628. if isinstance(pattern, URLPattern)
  629. else str(pattern.pattern)
  630. )
  631. self._extend_tried(tried, pattern, sub_match.tried)
  632. return ResolverMatch(
  633. sub_match.func,
  634. sub_match_args,
  635. sub_match_dict,
  636. sub_match.url_name,
  637. [self.app_name] + sub_match.app_names,
  638. [self.namespace] + sub_match.namespaces,
  639. self._join_route(current_route, sub_match.route),
  640. tried,
  641. captured_kwargs=sub_match.captured_kwargs,
  642. extra_kwargs={
  643. **self.default_kwargs,
  644. **sub_match.extra_kwargs,
  645. },
  646. )
  647. tried.append([pattern])
  648. raise Resolver404({"tried": tried, "path": new_path})
  649. raise Resolver404({"path": path})
  650. @cached_property
  651. def urlconf_module(self):
  652. if isinstance(self.urlconf_name, str):
  653. return import_module(self.urlconf_name)
  654. else:
  655. return self.urlconf_name
  656. @cached_property
  657. def url_patterns(self):
  658. # urlconf_module might be a valid set of patterns, so we default to it
  659. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  660. try:
  661. iter(patterns)
  662. except TypeError as e:
  663. msg = (
  664. "The included URLconf '{name}' does not appear to have "
  665. "any patterns in it. If you see the 'urlpatterns' variable "
  666. "with valid patterns in the file then the issue is probably "
  667. "caused by a circular import."
  668. )
  669. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
  670. return patterns
  671. def resolve_error_handler(self, view_type):
  672. callback = getattr(self.urlconf_module, "handler%s" % view_type, None)
  673. if not callback:
  674. # No handler specified in file; use lazy import, since
  675. # django.conf.urls imports this file.
  676. from django.conf import urls
  677. callback = getattr(urls, "handler%s" % view_type)
  678. return get_callable(callback)
  679. def reverse(self, lookup_view, *args, **kwargs):
  680. return self._reverse_with_prefix(lookup_view, "", *args, **kwargs)
  681. def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
  682. if args and kwargs:
  683. raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
  684. if not self._populated:
  685. self._populate()
  686. possibilities = self.reverse_dict.getlist(lookup_view)
  687. for possibility, pattern, defaults, converters in possibilities:
  688. for result, params in possibility:
  689. if args:
  690. if len(args) != len(params):
  691. continue
  692. candidate_subs = dict(zip(params, args))
  693. else:
  694. if set(kwargs).symmetric_difference(params).difference(defaults):
  695. continue
  696. matches = True
  697. for k, v in defaults.items():
  698. if k in params:
  699. continue
  700. if kwargs.get(k, v) != v:
  701. matches = False
  702. break
  703. if not matches:
  704. continue
  705. candidate_subs = kwargs
  706. # Convert the candidate subs to text using Converter.to_url().
  707. text_candidate_subs = {}
  708. match = True
  709. for k, v in candidate_subs.items():
  710. if k in converters:
  711. try:
  712. text_candidate_subs[k] = converters[k].to_url(v)
  713. except ValueError:
  714. match = False
  715. break
  716. else:
  717. text_candidate_subs[k] = str(v)
  718. if not match:
  719. continue
  720. # WSGI provides decoded URLs, without %xx escapes, and the URL
  721. # resolver operates on such URLs. First substitute arguments
  722. # without quoting to build a decoded URL and look for a match.
  723. # Then, if we have a match, redo the substitution with quoted
  724. # arguments in order to return a properly encoded URL.
  725. candidate_pat = _prefix.replace("%", "%%") + result
  726. if re.search(
  727. "^%s%s" % (re.escape(_prefix), pattern),
  728. candidate_pat % text_candidate_subs,
  729. ):
  730. # safe characters from `pchar` definition of RFC 3986
  731. url = quote(
  732. candidate_pat % text_candidate_subs,
  733. safe=RFC3986_SUBDELIMS + "/~:@",
  734. )
  735. # Don't allow construction of scheme relative urls.
  736. return escape_leading_slashes(url)
  737. # lookup_view can be URL name or callable, but callables are not
  738. # friendly in error messages.
  739. m = getattr(lookup_view, "__module__", None)
  740. n = getattr(lookup_view, "__name__", None)
  741. if m is not None and n is not None:
  742. lookup_view_s = "%s.%s" % (m, n)
  743. else:
  744. lookup_view_s = lookup_view
  745. patterns = [pattern for (_, pattern, _, _) in possibilities]
  746. if patterns:
  747. if args:
  748. arg_msg = "arguments '%s'" % (args,)
  749. elif kwargs:
  750. arg_msg = "keyword arguments '%s'" % kwargs
  751. else:
  752. arg_msg = "no arguments"
  753. msg = "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % (
  754. lookup_view_s,
  755. arg_msg,
  756. len(patterns),
  757. patterns,
  758. )
  759. else:
  760. msg = (
  761. "Reverse for '%(view)s' not found. '%(view)s' is not "
  762. "a valid view function or pattern name." % {"view": lookup_view_s}
  763. )
  764. raise NoReverseMatch(msg)