resolvers.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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(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. class URLResolver:
  381. def __init__(
  382. self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None
  383. ):
  384. self.pattern = pattern
  385. # urlconf_name is the dotted Python path to the module defining
  386. # urlpatterns. It may also be an object with an urlpatterns attribute
  387. # or urlpatterns itself.
  388. self.urlconf_name = urlconf_name
  389. self.callback = None
  390. self.default_kwargs = default_kwargs or {}
  391. self.namespace = namespace
  392. self.app_name = app_name
  393. self._reverse_dict = {}
  394. self._namespace_dict = {}
  395. self._app_dict = {}
  396. self._populated = False
  397. self._local = Local()
  398. def __repr__(self):
  399. if isinstance(self.urlconf_name, list) and self.urlconf_name:
  400. # Don't bother to output the whole list, it can be huge
  401. urlconf_repr = "<%s list>" % self.urlconf_name[0].__class__.__name__
  402. else:
  403. urlconf_repr = repr(self.urlconf_name)
  404. return "<%s %s (%s:%s) %s>" % (
  405. self.__class__.__name__,
  406. urlconf_repr,
  407. self.app_name,
  408. self.namespace,
  409. self.pattern.describe(),
  410. )
  411. def check(self):
  412. messages = []
  413. for pattern in self.url_patterns:
  414. messages.extend(check_resolver(pattern))
  415. messages.extend(self._check_custom_error_handlers())
  416. return messages or self.pattern.check()
  417. def _check_custom_error_handlers(self):
  418. messages = []
  419. # All handlers take (request, exception) arguments except handler500
  420. # which takes (request).
  421. for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]:
  422. try:
  423. handler = self.resolve_error_handler(status_code)
  424. except (ImportError, ViewDoesNotExist) as e:
  425. path = getattr(self.urlconf_module, "handler%s" % status_code)
  426. msg = (
  427. "The custom handler{status_code} view '{path}' could not be "
  428. "imported."
  429. ).format(status_code=status_code, path=path)
  430. messages.append(Error(msg, hint=str(e), id="urls.E008"))
  431. continue
  432. signature = inspect.signature(handler)
  433. args = [None] * num_parameters
  434. try:
  435. signature.bind(*args)
  436. except TypeError:
  437. msg = (
  438. "The custom handler{status_code} view '{path}' does not "
  439. "take the correct number of arguments ({args})."
  440. ).format(
  441. status_code=status_code,
  442. path=handler.__module__ + "." + handler.__qualname__,
  443. args="request, exception" if num_parameters == 2 else "request",
  444. )
  445. messages.append(Error(msg, id="urls.E007"))
  446. return messages
  447. def _populate(self):
  448. # Short-circuit if called recursively in this thread to prevent
  449. # infinite recursion. Concurrent threads may call this at the same
  450. # time and will need to continue, so set 'populating' on a
  451. # thread-local variable.
  452. if getattr(self._local, "populating", False):
  453. return
  454. try:
  455. self._local.populating = True
  456. lookups = MultiValueDict()
  457. namespaces = {}
  458. apps = {}
  459. language_code = get_language()
  460. for url_pattern in reversed(self.url_patterns):
  461. p_pattern = url_pattern.pattern.regex.pattern
  462. if p_pattern.startswith("^"):
  463. p_pattern = p_pattern[1:]
  464. if isinstance(url_pattern, URLPattern):
  465. bits = normalize(url_pattern.pattern.regex.pattern)
  466. lookups.appendlist(
  467. url_pattern.callback,
  468. (
  469. bits,
  470. p_pattern,
  471. url_pattern.default_args,
  472. url_pattern.pattern.converters,
  473. ),
  474. )
  475. if url_pattern.name is not None:
  476. lookups.appendlist(
  477. url_pattern.name,
  478. (
  479. bits,
  480. p_pattern,
  481. url_pattern.default_args,
  482. url_pattern.pattern.converters,
  483. ),
  484. )
  485. else: # url_pattern is a URLResolver.
  486. url_pattern._populate()
  487. if url_pattern.app_name:
  488. apps.setdefault(url_pattern.app_name, []).append(
  489. url_pattern.namespace
  490. )
  491. namespaces[url_pattern.namespace] = (p_pattern, url_pattern)
  492. else:
  493. for name in url_pattern.reverse_dict:
  494. for (
  495. matches,
  496. pat,
  497. defaults,
  498. converters,
  499. ) in url_pattern.reverse_dict.getlist(name):
  500. new_matches = normalize(p_pattern + pat)
  501. lookups.appendlist(
  502. name,
  503. (
  504. new_matches,
  505. p_pattern + pat,
  506. {**defaults, **url_pattern.default_kwargs},
  507. {
  508. **self.pattern.converters,
  509. **url_pattern.pattern.converters,
  510. **converters,
  511. },
  512. ),
  513. )
  514. for namespace, (
  515. prefix,
  516. sub_pattern,
  517. ) in url_pattern.namespace_dict.items():
  518. current_converters = url_pattern.pattern.converters
  519. sub_pattern.pattern.converters.update(current_converters)
  520. namespaces[namespace] = (p_pattern + prefix, sub_pattern)
  521. for app_name, namespace_list in url_pattern.app_dict.items():
  522. apps.setdefault(app_name, []).extend(namespace_list)
  523. self._namespace_dict[language_code] = namespaces
  524. self._app_dict[language_code] = apps
  525. self._reverse_dict[language_code] = lookups
  526. self._populated = True
  527. finally:
  528. self._local.populating = False
  529. @property
  530. def reverse_dict(self):
  531. language_code = get_language()
  532. if language_code not in self._reverse_dict:
  533. self._populate()
  534. return self._reverse_dict[language_code]
  535. @property
  536. def namespace_dict(self):
  537. language_code = get_language()
  538. if language_code not in self._namespace_dict:
  539. self._populate()
  540. return self._namespace_dict[language_code]
  541. @property
  542. def app_dict(self):
  543. language_code = get_language()
  544. if language_code not in self._app_dict:
  545. self._populate()
  546. return self._app_dict[language_code]
  547. @staticmethod
  548. def _extend_tried(tried, pattern, sub_tried=None):
  549. if sub_tried is None:
  550. tried.append([pattern])
  551. else:
  552. tried.extend([pattern, *t] for t in sub_tried)
  553. @staticmethod
  554. def _join_route(route1, route2):
  555. """Join two routes, without the starting ^ in the second route."""
  556. if not route1:
  557. return route2
  558. if route2.startswith("^"):
  559. route2 = route2[1:]
  560. return route1 + route2
  561. def resolve(self, path):
  562. path = str(path) # path may be a reverse_lazy object
  563. tried = []
  564. match = self.pattern.match(path)
  565. if match:
  566. new_path, args, kwargs = match
  567. for pattern in self.url_patterns:
  568. try:
  569. sub_match = pattern.resolve(new_path)
  570. except Resolver404 as e:
  571. self._extend_tried(tried, pattern, e.args[0].get("tried"))
  572. else:
  573. if sub_match:
  574. # Merge captured arguments in match with submatch
  575. sub_match_dict = {**kwargs, **self.default_kwargs}
  576. # Update the sub_match_dict with the kwargs from the sub_match.
  577. sub_match_dict.update(sub_match.kwargs)
  578. # If there are *any* named groups, ignore all non-named groups.
  579. # Otherwise, pass all non-named arguments as positional
  580. # arguments.
  581. sub_match_args = sub_match.args
  582. if not sub_match_dict:
  583. sub_match_args = args + sub_match.args
  584. current_route = (
  585. ""
  586. if isinstance(pattern, URLPattern)
  587. else str(pattern.pattern)
  588. )
  589. self._extend_tried(tried, pattern, sub_match.tried)
  590. return ResolverMatch(
  591. sub_match.func,
  592. sub_match_args,
  593. sub_match_dict,
  594. sub_match.url_name,
  595. [self.app_name] + sub_match.app_names,
  596. [self.namespace] + sub_match.namespaces,
  597. self._join_route(current_route, sub_match.route),
  598. tried,
  599. captured_kwargs=sub_match.captured_kwargs,
  600. extra_kwargs={
  601. **self.default_kwargs,
  602. **sub_match.extra_kwargs,
  603. },
  604. )
  605. tried.append([pattern])
  606. raise Resolver404({"tried": tried, "path": new_path})
  607. raise Resolver404({"path": path})
  608. @cached_property
  609. def urlconf_module(self):
  610. if isinstance(self.urlconf_name, str):
  611. return import_module(self.urlconf_name)
  612. else:
  613. return self.urlconf_name
  614. @cached_property
  615. def url_patterns(self):
  616. # urlconf_module might be a valid set of patterns, so we default to it
  617. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  618. try:
  619. iter(patterns)
  620. except TypeError as e:
  621. msg = (
  622. "The included URLconf '{name}' does not appear to have "
  623. "any patterns in it. If you see the 'urlpatterns' variable "
  624. "with valid patterns in the file then the issue is probably "
  625. "caused by a circular import."
  626. )
  627. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
  628. return patterns
  629. def resolve_error_handler(self, view_type):
  630. callback = getattr(self.urlconf_module, "handler%s" % view_type, None)
  631. if not callback:
  632. # No handler specified in file; use lazy import, since
  633. # django.conf.urls imports this file.
  634. from django.conf import urls
  635. callback = getattr(urls, "handler%s" % view_type)
  636. return get_callable(callback)
  637. def reverse(self, lookup_view, *args, **kwargs):
  638. return self._reverse_with_prefix(lookup_view, "", *args, **kwargs)
  639. def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
  640. if args and kwargs:
  641. raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
  642. if not self._populated:
  643. self._populate()
  644. possibilities = self.reverse_dict.getlist(lookup_view)
  645. for possibility, pattern, defaults, converters in possibilities:
  646. for result, params in possibility:
  647. if args:
  648. if len(args) != len(params):
  649. continue
  650. candidate_subs = dict(zip(params, args))
  651. else:
  652. if set(kwargs).symmetric_difference(params).difference(defaults):
  653. continue
  654. matches = True
  655. for k, v in defaults.items():
  656. if k in params:
  657. continue
  658. if kwargs.get(k, v) != v:
  659. matches = False
  660. break
  661. if not matches:
  662. continue
  663. candidate_subs = kwargs
  664. # Convert the candidate subs to text using Converter.to_url().
  665. text_candidate_subs = {}
  666. match = True
  667. for k, v in candidate_subs.items():
  668. if k in converters:
  669. try:
  670. text_candidate_subs[k] = converters[k].to_url(v)
  671. except ValueError:
  672. match = False
  673. break
  674. else:
  675. text_candidate_subs[k] = str(v)
  676. if not match:
  677. continue
  678. # WSGI provides decoded URLs, without %xx escapes, and the URL
  679. # resolver operates on such URLs. First substitute arguments
  680. # without quoting to build a decoded URL and look for a match.
  681. # Then, if we have a match, redo the substitution with quoted
  682. # arguments in order to return a properly encoded URL.
  683. candidate_pat = _prefix.replace("%", "%%") + result
  684. if re.search(
  685. "^%s%s" % (re.escape(_prefix), pattern),
  686. candidate_pat % text_candidate_subs,
  687. ):
  688. # safe characters from `pchar` definition of RFC 3986
  689. url = quote(
  690. candidate_pat % text_candidate_subs,
  691. safe=RFC3986_SUBDELIMS + "/~:@",
  692. )
  693. # Don't allow construction of scheme relative urls.
  694. return escape_leading_slashes(url)
  695. # lookup_view can be URL name or callable, but callables are not
  696. # friendly in error messages.
  697. m = getattr(lookup_view, "__module__", None)
  698. n = getattr(lookup_view, "__name__", None)
  699. if m is not None and n is not None:
  700. lookup_view_s = "%s.%s" % (m, n)
  701. else:
  702. lookup_view_s = lookup_view
  703. patterns = [pattern for (_, pattern, _, _) in possibilities]
  704. if patterns:
  705. if args:
  706. arg_msg = "arguments '%s'" % (args,)
  707. elif kwargs:
  708. arg_msg = "keyword arguments '%s'" % kwargs
  709. else:
  710. arg_msg = "no arguments"
  711. msg = "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % (
  712. lookup_view_s,
  713. arg_msg,
  714. len(patterns),
  715. patterns,
  716. )
  717. else:
  718. msg = (
  719. "Reverse for '%(view)s' not found. '%(view)s' is not "
  720. "a valid view function or pattern name." % {"view": lookup_view_s}
  721. )
  722. raise NoReverseMatch(msg)