2
0

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