resolvers.py 31 KB

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