resolvers.py 27 KB

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