Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

resolvers.py 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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.lru_cache(maxsize=None)
  96. def _get_cached_resolver(urlconf=None):
  97. return URLResolver(RegexPattern(r"^/"), urlconf)
  98. @functools.lru_cache(maxsize=None)
  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 = self._check_pattern_startswith_slash()
  281. route = self._route
  282. if "(?P<" in route or route.startswith("^") or route.endswith("$"):
  283. warnings.append(
  284. Warning(
  285. "Your URL pattern {} has a route that contains '(?P<', begins "
  286. "with a '^', or ends with a '$'. This was likely an oversight "
  287. "when migrating to django.urls.path().".format(self.describe()),
  288. id="2_0.W001",
  289. )
  290. )
  291. return warnings
  292. def _compile(self, route):
  293. return re.compile(_route_to_regex(route, self._is_endpoint)[0])
  294. def __str__(self):
  295. return str(self._route)
  296. class LocalePrefixPattern:
  297. def __init__(self, prefix_default_language=True):
  298. self.prefix_default_language = prefix_default_language
  299. self.converters = {}
  300. @property
  301. def regex(self):
  302. # This is only used by reverse() and cached in _reverse_dict.
  303. return re.compile(re.escape(self.language_prefix))
  304. @property
  305. def language_prefix(self):
  306. language_code = get_language() or settings.LANGUAGE_CODE
  307. if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
  308. return ""
  309. else:
  310. return "%s/" % language_code
  311. def match(self, path):
  312. language_prefix = self.language_prefix
  313. if path.startswith(language_prefix):
  314. return path[len(language_prefix) :], (), {}
  315. return None
  316. def check(self):
  317. return []
  318. def describe(self):
  319. return "'{}'".format(self)
  320. def __str__(self):
  321. return self.language_prefix
  322. class URLPattern:
  323. def __init__(self, pattern, callback, default_args=None, name=None):
  324. self.pattern = pattern
  325. self.callback = callback # the view
  326. self.default_args = default_args or {}
  327. self.name = name
  328. def __repr__(self):
  329. return "<%s %s>" % (self.__class__.__name__, self.pattern.describe())
  330. def check(self):
  331. warnings = self._check_pattern_name()
  332. warnings.extend(self.pattern.check())
  333. warnings.extend(self._check_callback())
  334. return warnings
  335. def _check_pattern_name(self):
  336. """
  337. Check that the pattern name does not contain a colon.
  338. """
  339. if self.pattern.name is not None and ":" in self.pattern.name:
  340. warning = Warning(
  341. "Your URL pattern {} has a name including a ':'. Remove the colon, to "
  342. "avoid ambiguous namespace references.".format(self.pattern.describe()),
  343. id="urls.W003",
  344. )
  345. return [warning]
  346. else:
  347. return []
  348. def _check_callback(self):
  349. from django.views import View
  350. view = self.callback
  351. if inspect.isclass(view) and issubclass(view, View):
  352. return [
  353. Error(
  354. "Your URL pattern %s has an invalid view, pass %s.as_view() "
  355. "instead of %s."
  356. % (
  357. self.pattern.describe(),
  358. view.__name__,
  359. view.__name__,
  360. ),
  361. id="urls.E009",
  362. )
  363. ]
  364. return []
  365. def resolve(self, path):
  366. match = self.pattern.match(path)
  367. if match:
  368. new_path, args, captured_kwargs = match
  369. # Pass any default args as **kwargs.
  370. kwargs = {**captured_kwargs, **self.default_args}
  371. return ResolverMatch(
  372. self.callback,
  373. args,
  374. kwargs,
  375. self.pattern.name,
  376. route=str(self.pattern),
  377. captured_kwargs=captured_kwargs,
  378. extra_kwargs=self.default_args,
  379. )
  380. @cached_property
  381. def lookup_str(self):
  382. """
  383. A string that identifies the view (e.g. 'path.to.view_function' or
  384. 'path.to.ClassBasedView').
  385. """
  386. callback = self.callback
  387. if isinstance(callback, functools.partial):
  388. callback = callback.func
  389. if hasattr(callback, "view_class"):
  390. callback = callback.view_class
  391. elif not hasattr(callback, "__name__"):
  392. return callback.__module__ + "." + callback.__class__.__name__
  393. return callback.__module__ + "." + callback.__qualname__
  394. class URLResolver:
  395. def __init__(
  396. self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None
  397. ):
  398. self.pattern = pattern
  399. # urlconf_name is the dotted Python path to the module defining
  400. # urlpatterns. It may also be an object with an urlpatterns attribute
  401. # or urlpatterns itself.
  402. self.urlconf_name = urlconf_name
  403. self.callback = None
  404. self.default_kwargs = default_kwargs or {}
  405. self.namespace = namespace
  406. self.app_name = app_name
  407. self._reverse_dict = {}
  408. self._namespace_dict = {}
  409. self._app_dict = {}
  410. # set of dotted paths to all functions and classes that are used in
  411. # urlpatterns
  412. self._callback_strs = set()
  413. self._populated = False
  414. self._local = Local()
  415. def __repr__(self):
  416. if isinstance(self.urlconf_name, list) and self.urlconf_name:
  417. # Don't bother to output the whole list, it can be huge
  418. urlconf_repr = "<%s list>" % self.urlconf_name[0].__class__.__name__
  419. else:
  420. urlconf_repr = repr(self.urlconf_name)
  421. return "<%s %s (%s:%s) %s>" % (
  422. self.__class__.__name__,
  423. urlconf_repr,
  424. self.app_name,
  425. self.namespace,
  426. self.pattern.describe(),
  427. )
  428. def check(self):
  429. messages = []
  430. for pattern in self.url_patterns:
  431. messages.extend(check_resolver(pattern))
  432. messages.extend(self._check_custom_error_handlers())
  433. return messages or self.pattern.check()
  434. def _check_custom_error_handlers(self):
  435. messages = []
  436. # All handlers take (request, exception) arguments except handler500
  437. # which takes (request).
  438. for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]:
  439. try:
  440. handler = self.resolve_error_handler(status_code)
  441. except (ImportError, ViewDoesNotExist) as e:
  442. path = getattr(self.urlconf_module, "handler%s" % status_code)
  443. msg = (
  444. "The custom handler{status_code} view '{path}' could not be "
  445. "imported."
  446. ).format(status_code=status_code, path=path)
  447. messages.append(Error(msg, hint=str(e), id="urls.E008"))
  448. continue
  449. signature = inspect.signature(handler)
  450. args = [None] * num_parameters
  451. try:
  452. signature.bind(*args)
  453. except TypeError:
  454. msg = (
  455. "The custom handler{status_code} view '{path}' does not "
  456. "take the correct number of arguments ({args})."
  457. ).format(
  458. status_code=status_code,
  459. path=handler.__module__ + "." + handler.__qualname__,
  460. args="request, exception" if num_parameters == 2 else "request",
  461. )
  462. messages.append(Error(msg, id="urls.E007"))
  463. return messages
  464. def _populate(self):
  465. # Short-circuit if called recursively in this thread to prevent
  466. # infinite recursion. Concurrent threads may call this at the same
  467. # time and will need to continue, so set 'populating' on a
  468. # thread-local variable.
  469. if getattr(self._local, "populating", False):
  470. return
  471. try:
  472. self._local.populating = True
  473. lookups = MultiValueDict()
  474. namespaces = {}
  475. apps = {}
  476. language_code = get_language()
  477. for url_pattern in reversed(self.url_patterns):
  478. p_pattern = url_pattern.pattern.regex.pattern
  479. if p_pattern.startswith("^"):
  480. p_pattern = p_pattern[1:]
  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. if route2.startswith("^"):
  578. route2 = route2[1:]
  579. return route1 + route2
  580. def _is_callback(self, name):
  581. if not self._populated:
  582. self._populate()
  583. return name in self._callback_strs
  584. def resolve(self, path):
  585. path = str(path) # path may be a reverse_lazy object
  586. tried = []
  587. match = self.pattern.match(path)
  588. if match:
  589. new_path, args, kwargs = match
  590. for pattern in self.url_patterns:
  591. try:
  592. sub_match = pattern.resolve(new_path)
  593. except Resolver404 as e:
  594. self._extend_tried(tried, pattern, e.args[0].get("tried"))
  595. else:
  596. if sub_match:
  597. # Merge captured arguments in match with submatch
  598. sub_match_dict = {**kwargs, **self.default_kwargs}
  599. # Update the sub_match_dict with the kwargs from the sub_match.
  600. sub_match_dict.update(sub_match.kwargs)
  601. # If there are *any* named groups, ignore all non-named groups.
  602. # Otherwise, pass all non-named arguments as positional
  603. # arguments.
  604. sub_match_args = sub_match.args
  605. if not sub_match_dict:
  606. sub_match_args = args + sub_match.args
  607. current_route = (
  608. ""
  609. if isinstance(pattern, URLPattern)
  610. else str(pattern.pattern)
  611. )
  612. self._extend_tried(tried, pattern, sub_match.tried)
  613. return ResolverMatch(
  614. sub_match.func,
  615. sub_match_args,
  616. sub_match_dict,
  617. sub_match.url_name,
  618. [self.app_name] + sub_match.app_names,
  619. [self.namespace] + sub_match.namespaces,
  620. self._join_route(current_route, sub_match.route),
  621. tried,
  622. captured_kwargs=sub_match.captured_kwargs,
  623. extra_kwargs={
  624. **self.default_kwargs,
  625. **sub_match.extra_kwargs,
  626. },
  627. )
  628. tried.append([pattern])
  629. raise Resolver404({"tried": tried, "path": new_path})
  630. raise Resolver404({"path": path})
  631. @cached_property
  632. def urlconf_module(self):
  633. if isinstance(self.urlconf_name, str):
  634. return import_module(self.urlconf_name)
  635. else:
  636. return self.urlconf_name
  637. @cached_property
  638. def url_patterns(self):
  639. # urlconf_module might be a valid set of patterns, so we default to it
  640. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  641. try:
  642. iter(patterns)
  643. except TypeError as e:
  644. msg = (
  645. "The included URLconf '{name}' does not appear to have "
  646. "any patterns in it. If you see the 'urlpatterns' variable "
  647. "with valid patterns in the file then the issue is probably "
  648. "caused by a circular import."
  649. )
  650. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
  651. return patterns
  652. def resolve_error_handler(self, view_type):
  653. callback = getattr(self.urlconf_module, "handler%s" % view_type, None)
  654. if not callback:
  655. # No handler specified in file; use lazy import, since
  656. # django.conf.urls imports this file.
  657. from django.conf import urls
  658. callback = getattr(urls, "handler%s" % view_type)
  659. return get_callable(callback)
  660. def reverse(self, lookup_view, *args, **kwargs):
  661. return self._reverse_with_prefix(lookup_view, "", *args, **kwargs)
  662. def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
  663. if args and kwargs:
  664. raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
  665. if not self._populated:
  666. self._populate()
  667. possibilities = self.reverse_dict.getlist(lookup_view)
  668. for possibility, pattern, defaults, converters in possibilities:
  669. for result, params in possibility:
  670. if args:
  671. if len(args) != len(params):
  672. continue
  673. candidate_subs = dict(zip(params, args))
  674. else:
  675. if set(kwargs).symmetric_difference(params).difference(defaults):
  676. continue
  677. matches = True
  678. for k, v in defaults.items():
  679. if k in params:
  680. continue
  681. if kwargs.get(k, v) != v:
  682. matches = False
  683. break
  684. if not matches:
  685. continue
  686. candidate_subs = kwargs
  687. # Convert the candidate subs to text using Converter.to_url().
  688. text_candidate_subs = {}
  689. match = True
  690. for k, v in candidate_subs.items():
  691. if k in converters:
  692. try:
  693. text_candidate_subs[k] = converters[k].to_url(v)
  694. except ValueError:
  695. match = False
  696. break
  697. else:
  698. text_candidate_subs[k] = str(v)
  699. if not match:
  700. continue
  701. # WSGI provides decoded URLs, without %xx escapes, and the URL
  702. # resolver operates on such URLs. First substitute arguments
  703. # without quoting to build a decoded URL and look for a match.
  704. # Then, if we have a match, redo the substitution with quoted
  705. # arguments in order to return a properly encoded URL.
  706. candidate_pat = _prefix.replace("%", "%%") + result
  707. if re.search(
  708. "^%s%s" % (re.escape(_prefix), pattern),
  709. candidate_pat % text_candidate_subs,
  710. ):
  711. # safe characters from `pchar` definition of RFC 3986
  712. url = quote(
  713. candidate_pat % text_candidate_subs,
  714. safe=RFC3986_SUBDELIMS + "/~:@",
  715. )
  716. # Don't allow construction of scheme relative urls.
  717. return escape_leading_slashes(url)
  718. # lookup_view can be URL name or callable, but callables are not
  719. # friendly in error messages.
  720. m = getattr(lookup_view, "__module__", None)
  721. n = getattr(lookup_view, "__name__", None)
  722. if m is not None and n is not None:
  723. lookup_view_s = "%s.%s" % (m, n)
  724. else:
  725. lookup_view_s = lookup_view
  726. patterns = [pattern for (_, pattern, _, _) in possibilities]
  727. if patterns:
  728. if args:
  729. arg_msg = "arguments '%s'" % (args,)
  730. elif kwargs:
  731. arg_msg = "keyword arguments '%s'" % kwargs
  732. else:
  733. arg_msg = "no arguments"
  734. msg = "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % (
  735. lookup_view_s,
  736. arg_msg,
  737. len(patterns),
  738. patterns,
  739. )
  740. else:
  741. msg = (
  742. "Reverse for '%(view)s' not found. '%(view)s' is not "
  743. "a valid view function or pattern name." % {"view": lookup_view_s}
  744. )
  745. raise NoReverseMatch(msg)