urlresolvers.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. """
  2. This module converts requested URLs to callback view functions.
  3. RegexURLResolver is the main class here. Its resolve() method takes a URL (as
  4. a string) and returns a tuple in this format:
  5. (view_function, function_args, function_kwargs)
  6. """
  7. from __future__ import unicode_literals
  8. import functools
  9. import re
  10. import warnings
  11. from importlib import import_module
  12. from threading import local
  13. from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
  14. from django.http import Http404
  15. from django.utils import lru_cache, six
  16. from django.utils.datastructures import MultiValueDict
  17. from django.utils.deprecation import RemovedInDjango110Warning
  18. from django.utils.encoding import force_str, force_text, iri_to_uri
  19. from django.utils.functional import cached_property, lazy
  20. from django.utils.http import RFC3986_SUBDELIMS, urlquote
  21. from django.utils.module_loading import module_has_submodule
  22. from django.utils.regex_helper import normalize
  23. from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
  24. from django.utils.translation import get_language, override
  25. # SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for
  26. # the current thread (which is the only one we ever access), it is assumed to
  27. # be empty.
  28. _prefixes = local()
  29. # Overridden URLconfs for each thread are stored here.
  30. _urlconfs = local()
  31. class ResolverMatch(object):
  32. def __init__(self, func, args, kwargs, url_name=None, app_names=None, namespaces=None):
  33. self.func = func
  34. self.args = args
  35. self.kwargs = kwargs
  36. self.url_name = url_name
  37. # If a URLRegexResolver doesn't have a namespace or app_name, it passes
  38. # in an empty value.
  39. self.app_names = [x for x in app_names if x] if app_names else []
  40. self.app_name = ':'.join(self.app_names)
  41. if namespaces:
  42. self.namespaces = [x for x in namespaces if x]
  43. else:
  44. self.namespaces = []
  45. self.namespace = ':'.join(self.namespaces)
  46. if not hasattr(func, '__name__'):
  47. # A class-based view
  48. self._func_path = '.'.join([func.__class__.__module__, func.__class__.__name__])
  49. else:
  50. # A function-based view
  51. self._func_path = '.'.join([func.__module__, func.__name__])
  52. view_path = url_name or self._func_path
  53. self.view_name = ':'.join(self.namespaces + [view_path])
  54. def __getitem__(self, index):
  55. return (self.func, self.args, self.kwargs)[index]
  56. def __repr__(self):
  57. return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_names=%s, namespaces=%s)" % (
  58. self._func_path, self.args, self.kwargs, self.url_name, self.app_names, self.namespaces)
  59. class Resolver404(Http404):
  60. pass
  61. class NoReverseMatch(Exception):
  62. pass
  63. @lru_cache.lru_cache(maxsize=None)
  64. def get_callable(lookup_view, can_fail=False):
  65. """
  66. Return a callable corresponding to lookup_view. This function is used
  67. by both resolve() and reverse(), so can_fail allows the caller to choose
  68. between returning the input as is and raising an exception when the input
  69. string can't be interpreted as an import path.
  70. If lookup_view is already a callable, return it.
  71. If lookup_view is a string import path that can be resolved to a callable,
  72. import that callable and return it.
  73. If lookup_view is some other kind of string and can_fail is True, the string
  74. is returned as is. If can_fail is False, an exception is raised (either
  75. ImportError or ViewDoesNotExist).
  76. """
  77. if callable(lookup_view):
  78. return lookup_view
  79. if not isinstance(lookup_view, six.string_types):
  80. raise ViewDoesNotExist(
  81. "'%s' is not a callable or a dot-notation path" % lookup_view
  82. )
  83. mod_name, func_name = get_mod_func(lookup_view)
  84. if not func_name: # No '.' in lookup_view
  85. if can_fail:
  86. return lookup_view
  87. else:
  88. raise ImportError(
  89. "Could not import '%s'. The path must be fully qualified." %
  90. lookup_view)
  91. try:
  92. mod = import_module(mod_name)
  93. except ImportError:
  94. if can_fail:
  95. return lookup_view
  96. else:
  97. parentmod, submod = get_mod_func(mod_name)
  98. if submod and not module_has_submodule(import_module(parentmod), submod):
  99. raise ViewDoesNotExist(
  100. "Could not import '%s'. Parent module %s does not exist." %
  101. (lookup_view, mod_name))
  102. else:
  103. raise
  104. else:
  105. try:
  106. view_func = getattr(mod, func_name)
  107. except AttributeError:
  108. if can_fail:
  109. return lookup_view
  110. else:
  111. raise ViewDoesNotExist(
  112. "Could not import '%s'. View does not exist in module %s." %
  113. (lookup_view, mod_name))
  114. else:
  115. if not callable(view_func):
  116. # For backwards compatibility this is raised regardless of can_fail
  117. raise ViewDoesNotExist(
  118. "Could not import '%s.%s'. View is not callable." %
  119. (mod_name, func_name))
  120. return view_func
  121. @lru_cache.lru_cache(maxsize=None)
  122. def get_resolver(urlconf):
  123. if urlconf is None:
  124. from django.conf import settings
  125. urlconf = settings.ROOT_URLCONF
  126. return RegexURLResolver(r'^/', urlconf)
  127. @lru_cache.lru_cache(maxsize=None)
  128. def get_ns_resolver(ns_pattern, resolver):
  129. # Build a namespaced resolver for the given parent urlconf pattern.
  130. # This makes it possible to have captured parameters in the parent
  131. # urlconf pattern.
  132. ns_resolver = RegexURLResolver(ns_pattern, resolver.url_patterns)
  133. return RegexURLResolver(r'^/', [ns_resolver])
  134. def get_mod_func(callback):
  135. # Converts 'django.views.news.stories.story_detail' to
  136. # ['django.views.news.stories', 'story_detail']
  137. try:
  138. dot = callback.rindex('.')
  139. except ValueError:
  140. return callback, ''
  141. return callback[:dot], callback[dot + 1:]
  142. class LocaleRegexProvider(object):
  143. """
  144. A mixin to provide a default regex property which can vary by active
  145. language.
  146. """
  147. def __init__(self, regex):
  148. # regex is either a string representing a regular expression, or a
  149. # translatable string (using ugettext_lazy) representing a regular
  150. # expression.
  151. self._regex = regex
  152. self._regex_dict = {}
  153. @property
  154. def regex(self):
  155. """
  156. Returns a compiled regular expression, depending upon the activated
  157. language-code.
  158. """
  159. language_code = get_language()
  160. if language_code not in self._regex_dict:
  161. if isinstance(self._regex, six.string_types):
  162. regex = self._regex
  163. else:
  164. regex = force_text(self._regex)
  165. try:
  166. compiled_regex = re.compile(regex, re.UNICODE)
  167. except re.error as e:
  168. raise ImproperlyConfigured(
  169. '"%s" is not a valid regular expression: %s' %
  170. (regex, six.text_type(e)))
  171. self._regex_dict[language_code] = compiled_regex
  172. return self._regex_dict[language_code]
  173. class RegexURLPattern(LocaleRegexProvider):
  174. def __init__(self, regex, callback, default_args=None, name=None):
  175. LocaleRegexProvider.__init__(self, regex)
  176. # callback is either a string like 'foo.views.news.stories.story_detail'
  177. # which represents the path to a module and a view function name, or a
  178. # callable object (view).
  179. if callable(callback):
  180. self._callback = callback
  181. else:
  182. self._callback = None
  183. self._callback_str = callback
  184. self.default_args = default_args or {}
  185. self.name = name
  186. def __repr__(self):
  187. return force_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern))
  188. def add_prefix(self, prefix):
  189. """
  190. Adds the prefix string to a string-based callback.
  191. """
  192. if not prefix or not hasattr(self, '_callback_str'):
  193. return
  194. self._callback_str = prefix + '.' + self._callback_str
  195. def resolve(self, path):
  196. match = self.regex.search(path)
  197. if match:
  198. # If there are any named groups, use those as kwargs, ignoring
  199. # non-named groups. Otherwise, pass all non-named arguments as
  200. # positional arguments.
  201. kwargs = match.groupdict()
  202. if kwargs:
  203. args = ()
  204. else:
  205. args = match.groups()
  206. # In both cases, pass any extra_kwargs as **kwargs.
  207. kwargs.update(self.default_args)
  208. return ResolverMatch(self.callback, args, kwargs, self.name)
  209. @property
  210. def callback(self):
  211. if self._callback is not None:
  212. return self._callback
  213. self._callback = get_callable(self._callback_str)
  214. return self._callback
  215. class RegexURLResolver(LocaleRegexProvider):
  216. def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
  217. LocaleRegexProvider.__init__(self, regex)
  218. # urlconf_name is the dotted Python path to the module defining
  219. # urlpatterns. It may also be an object with an urlpatterns attribute
  220. # or urlpatterns itself.
  221. self.urlconf_name = urlconf_name
  222. self.callback = None
  223. self.default_kwargs = default_kwargs or {}
  224. self.namespace = namespace
  225. self.app_name = app_name
  226. self._reverse_dict = {}
  227. self._namespace_dict = {}
  228. self._app_dict = {}
  229. # set of dotted paths to all functions and classes that are used in
  230. # urlpatterns
  231. self._callback_strs = set()
  232. self._populated = False
  233. def __repr__(self):
  234. if isinstance(self.urlconf_name, list) and len(self.urlconf_name):
  235. # Don't bother to output the whole list, it can be huge
  236. urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
  237. else:
  238. urlconf_repr = repr(self.urlconf_name)
  239. return str('<%s %s (%s:%s) %s>') % (
  240. self.__class__.__name__, urlconf_repr, self.app_name,
  241. self.namespace, self.regex.pattern)
  242. def _populate(self):
  243. lookups = MultiValueDict()
  244. namespaces = {}
  245. apps = {}
  246. language_code = get_language()
  247. for pattern in reversed(self.url_patterns):
  248. if hasattr(pattern, '_callback_str'):
  249. self._callback_strs.add(pattern._callback_str)
  250. elif hasattr(pattern, '_callback'):
  251. callback = pattern._callback
  252. if isinstance(callback, functools.partial):
  253. callback = callback.func
  254. if not hasattr(callback, '__name__'):
  255. lookup_str = callback.__module__ + "." + callback.__class__.__name__
  256. else:
  257. lookup_str = callback.__module__ + "." + callback.__name__
  258. self._callback_strs.add(lookup_str)
  259. p_pattern = pattern.regex.pattern
  260. if p_pattern.startswith('^'):
  261. p_pattern = p_pattern[1:]
  262. if isinstance(pattern, RegexURLResolver):
  263. if pattern.namespace:
  264. namespaces[pattern.namespace] = (p_pattern, pattern)
  265. if pattern.app_name:
  266. apps.setdefault(pattern.app_name, []).append(pattern.namespace)
  267. else:
  268. parent_pat = pattern.regex.pattern
  269. for name in pattern.reverse_dict:
  270. for matches, pat, defaults in pattern.reverse_dict.getlist(name):
  271. new_matches = normalize(parent_pat + pat)
  272. lookups.appendlist(
  273. name,
  274. (
  275. new_matches,
  276. p_pattern + pat,
  277. dict(defaults, **pattern.default_kwargs),
  278. )
  279. )
  280. for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items():
  281. namespaces[namespace] = (p_pattern + prefix, sub_pattern)
  282. for app_name, namespace_list in pattern.app_dict.items():
  283. apps.setdefault(app_name, []).extend(namespace_list)
  284. self._callback_strs.update(pattern._callback_strs)
  285. else:
  286. bits = normalize(p_pattern)
  287. lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args))
  288. if pattern.name is not None:
  289. lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args))
  290. self._reverse_dict[language_code] = lookups
  291. self._namespace_dict[language_code] = namespaces
  292. self._app_dict[language_code] = apps
  293. self._populated = True
  294. @property
  295. def reverse_dict(self):
  296. language_code = get_language()
  297. if language_code not in self._reverse_dict:
  298. self._populate()
  299. return self._reverse_dict[language_code]
  300. @property
  301. def namespace_dict(self):
  302. language_code = get_language()
  303. if language_code not in self._namespace_dict:
  304. self._populate()
  305. return self._namespace_dict[language_code]
  306. @property
  307. def app_dict(self):
  308. language_code = get_language()
  309. if language_code not in self._app_dict:
  310. self._populate()
  311. return self._app_dict[language_code]
  312. def _is_callback(self, name):
  313. if not self._populated:
  314. self._populate()
  315. return name in self._callback_strs
  316. def resolve(self, path):
  317. path = force_text(path) # path may be a reverse_lazy object
  318. tried = []
  319. match = self.regex.search(path)
  320. if match:
  321. new_path = path[match.end():]
  322. for pattern in self.url_patterns:
  323. try:
  324. sub_match = pattern.resolve(new_path)
  325. except Resolver404 as e:
  326. sub_tried = e.args[0].get('tried')
  327. if sub_tried is not None:
  328. tried.extend([pattern] + t for t in sub_tried)
  329. else:
  330. tried.append([pattern])
  331. else:
  332. if sub_match:
  333. # Merge captured arguments in match with submatch
  334. sub_match_dict = dict(match.groupdict(), **self.default_kwargs)
  335. sub_match_dict.update(sub_match.kwargs)
  336. # If there are *any* named groups, ignore all non-named groups.
  337. # Otherwise, pass all non-named arguments as positional arguments.
  338. sub_match_args = sub_match.args
  339. if not sub_match_dict:
  340. sub_match_args = match.groups() + sub_match.args
  341. return ResolverMatch(
  342. sub_match.func,
  343. sub_match_args,
  344. sub_match_dict,
  345. sub_match.url_name,
  346. [self.app_name] + sub_match.app_names,
  347. [self.namespace] + sub_match.namespaces
  348. )
  349. tried.append([pattern])
  350. raise Resolver404({'tried': tried, 'path': new_path})
  351. raise Resolver404({'path': path})
  352. @cached_property
  353. def urlconf_module(self):
  354. if isinstance(self.urlconf_name, six.string_types):
  355. return import_module(self.urlconf_name)
  356. else:
  357. return self.urlconf_name
  358. @cached_property
  359. def url_patterns(self):
  360. # urlconf_module might be a valid set of patterns, so we default to it
  361. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  362. try:
  363. iter(patterns)
  364. except TypeError:
  365. msg = (
  366. "The included urlconf '{name}' does not appear to have any "
  367. "patterns in it. If you see valid patterns in the file then "
  368. "the issue is probably caused by a circular import."
  369. )
  370. raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
  371. return patterns
  372. def resolve_error_handler(self, view_type):
  373. callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
  374. if not callback:
  375. # No handler specified in file; use default
  376. # Lazy import, since django.urls imports this file
  377. from django.conf import urls
  378. callback = getattr(urls, 'handler%s' % view_type)
  379. return get_callable(callback), {}
  380. def reverse(self, lookup_view, *args, **kwargs):
  381. return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)
  382. def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
  383. if args and kwargs:
  384. raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
  385. text_args = [force_text(v) for v in args]
  386. text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()}
  387. if not self._populated:
  388. self._populate()
  389. original_lookup = lookup_view
  390. try:
  391. if self._is_callback(lookup_view):
  392. lookup_view = get_callable(lookup_view, True)
  393. except (ImportError, AttributeError) as e:
  394. raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
  395. else:
  396. if not callable(original_lookup) and callable(lookup_view):
  397. warnings.warn(
  398. 'Reversing by dotted path is deprecated (%s).' % original_lookup,
  399. RemovedInDjango110Warning, stacklevel=3
  400. )
  401. possibilities = self.reverse_dict.getlist(lookup_view)
  402. for possibility, pattern, defaults in possibilities:
  403. for result, params in possibility:
  404. if args:
  405. if len(args) != len(params):
  406. continue
  407. candidate_subs = dict(zip(params, text_args))
  408. else:
  409. if (set(kwargs.keys()) | set(defaults.keys()) != set(params) |
  410. set(defaults.keys())):
  411. continue
  412. matches = True
  413. for k, v in defaults.items():
  414. if kwargs.get(k, v) != v:
  415. matches = False
  416. break
  417. if not matches:
  418. continue
  419. candidate_subs = text_kwargs
  420. # WSGI provides decoded URLs, without %xx escapes, and the URL
  421. # resolver operates on such URLs. First substitute arguments
  422. # without quoting to build a decoded URL and look for a match.
  423. # Then, if we have a match, redo the substitution with quoted
  424. # arguments in order to return a properly encoded URL.
  425. candidate_pat = _prefix.replace('%', '%%') + result
  426. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
  427. # safe characters from `pchar` definition of RFC 3986
  428. url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
  429. # Don't allow construction of scheme relative urls.
  430. if url.startswith('//'):
  431. url = '/%%2F%s' % url[2:]
  432. return url
  433. # lookup_view can be URL label, or dotted path, or callable, Any of
  434. # these can be passed in at the top, but callables are not friendly in
  435. # error messages.
  436. m = getattr(lookup_view, '__module__', None)
  437. n = getattr(lookup_view, '__name__', None)
  438. if m is not None and n is not None:
  439. lookup_view_s = "%s.%s" % (m, n)
  440. else:
  441. lookup_view_s = lookup_view
  442. patterns = [pattern for (possibility, pattern, defaults) in possibilities]
  443. raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword "
  444. "arguments '%s' not found. %d pattern(s) tried: %s" %
  445. (lookup_view_s, args, kwargs, len(patterns), patterns))
  446. class LocaleRegexURLResolver(RegexURLResolver):
  447. """
  448. A URL resolver that always matches the active language code as URL prefix.
  449. Rather than taking a regex argument, we just override the ``regex``
  450. function to always return the active language-code as regex.
  451. """
  452. def __init__(self, urlconf_name, default_kwargs=None, app_name=None, namespace=None):
  453. super(LocaleRegexURLResolver, self).__init__(
  454. None, urlconf_name, default_kwargs, app_name, namespace)
  455. @property
  456. def regex(self):
  457. language_code = get_language()
  458. if language_code not in self._regex_dict:
  459. regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
  460. self._regex_dict[language_code] = regex_compiled
  461. return self._regex_dict[language_code]
  462. def resolve(path, urlconf=None):
  463. if urlconf is None:
  464. urlconf = get_urlconf()
  465. return get_resolver(urlconf).resolve(path)
  466. def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
  467. if urlconf is None:
  468. urlconf = get_urlconf()
  469. resolver = get_resolver(urlconf)
  470. args = args or []
  471. kwargs = kwargs or {}
  472. prefix = get_script_prefix()
  473. if not isinstance(viewname, six.string_types):
  474. view = viewname
  475. else:
  476. parts = viewname.split(':')
  477. parts.reverse()
  478. view = parts[0]
  479. path = parts[1:]
  480. if current_app:
  481. current_path = current_app.split(':')
  482. current_path.reverse()
  483. else:
  484. current_path = None
  485. resolved_path = []
  486. ns_pattern = ''
  487. while path:
  488. ns = path.pop()
  489. current_ns = current_path.pop() if current_path else None
  490. # Lookup the name to see if it could be an app identifier
  491. try:
  492. app_list = resolver.app_dict[ns]
  493. # Yes! Path part matches an app in the current Resolver
  494. if current_ns and current_ns in app_list:
  495. # If we are reversing for a particular app,
  496. # use that namespace
  497. ns = current_ns
  498. elif ns not in app_list:
  499. # The name isn't shared by one of the instances
  500. # (i.e., the default) so just pick the first instance
  501. # as the default.
  502. ns = app_list[0]
  503. except KeyError:
  504. pass
  505. if ns != current_ns:
  506. current_path = None
  507. try:
  508. extra, resolver = resolver.namespace_dict[ns]
  509. resolved_path.append(ns)
  510. ns_pattern = ns_pattern + extra
  511. except KeyError as key:
  512. if resolved_path:
  513. raise NoReverseMatch(
  514. "%s is not a registered namespace inside '%s'" %
  515. (key, ':'.join(resolved_path)))
  516. else:
  517. raise NoReverseMatch("%s is not a registered namespace" %
  518. key)
  519. if ns_pattern:
  520. resolver = get_ns_resolver(ns_pattern, resolver)
  521. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  522. reverse_lazy = lazy(reverse, six.text_type)
  523. def clear_url_caches():
  524. get_callable.cache_clear()
  525. get_resolver.cache_clear()
  526. get_ns_resolver.cache_clear()
  527. def set_script_prefix(prefix):
  528. """
  529. Sets the script prefix for the current thread.
  530. """
  531. if not prefix.endswith('/'):
  532. prefix += '/'
  533. _prefixes.value = prefix
  534. def get_script_prefix():
  535. """
  536. Returns the currently active script prefix. Useful for client code that
  537. wishes to construct their own URLs manually (although accessing the request
  538. instance is normally going to be a lot cleaner).
  539. """
  540. return getattr(_prefixes, "value", '/')
  541. def clear_script_prefix():
  542. """
  543. Unsets the script prefix for the current thread.
  544. """
  545. try:
  546. del _prefixes.value
  547. except AttributeError:
  548. pass
  549. def set_urlconf(urlconf_name):
  550. """
  551. Sets the URLconf for the current thread (overriding the default one in
  552. settings). Set to None to revert back to the default.
  553. """
  554. if urlconf_name:
  555. _urlconfs.value = urlconf_name
  556. else:
  557. if hasattr(_urlconfs, "value"):
  558. del _urlconfs.value
  559. def get_urlconf(default=None):
  560. """
  561. Returns the root URLconf to use for the current thread if it has been
  562. changed from the default one.
  563. """
  564. return getattr(_urlconfs, "value", default)
  565. def is_valid_path(path, urlconf=None):
  566. """
  567. Returns True if the given path resolves against the default URL resolver,
  568. False otherwise.
  569. This is a convenience method to make working with "is this a match?" cases
  570. easier, avoiding unnecessarily indented try...except blocks.
  571. """
  572. try:
  573. resolve(path, urlconf)
  574. return True
  575. except Resolver404:
  576. return False
  577. def translate_url(url, lang_code):
  578. """
  579. Given a URL (absolute or relative), try to get its translated version in
  580. the `lang_code` language (either by i18n_patterns or by translated regex).
  581. Return the original URL if no translated version is found.
  582. """
  583. parsed = urlsplit(url)
  584. try:
  585. match = resolve(parsed.path)
  586. except Resolver404:
  587. pass
  588. else:
  589. to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name
  590. with override(lang_code):
  591. try:
  592. url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs)
  593. except NoReverseMatch:
  594. pass
  595. else:
  596. url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment))
  597. return url