trans_real.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. """Translation helper functions."""
  2. import functools
  3. import gettext as gettext_module
  4. import os
  5. import re
  6. import sys
  7. import warnings
  8. from asgiref.local import Local
  9. from django.apps import apps
  10. from django.conf import settings
  11. from django.conf.locale import LANG_INFO
  12. from django.core.exceptions import AppRegistryNotReady
  13. from django.core.signals import setting_changed
  14. from django.dispatch import receiver
  15. from django.utils.safestring import SafeData, mark_safe
  16. from . import to_language, to_locale
  17. # Translations are cached in a dictionary for every language.
  18. # The active translations are stored by threadid to make them thread local.
  19. _translations = {}
  20. _active = Local()
  21. # The default translation is based on the settings file.
  22. _default = None
  23. # magic gettext number to separate context from message
  24. CONTEXT_SEPARATOR = "\x04"
  25. # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9
  26. # and RFC 3066, section 2.1
  27. accept_language_re = re.compile(r'''
  28. ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # "en", "en-au", "x-y-z", "es-419", "*"
  29. (?:\s*;\s*q=(0(?:\.\d{,3})?|1(?:\.0{,3})?))? # Optional "q=1.00", "q=0.8"
  30. (?:\s*,\s*|$) # Multiple accepts per header.
  31. ''', re.VERBOSE)
  32. language_code_re = re.compile(
  33. r'^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$',
  34. re.IGNORECASE
  35. )
  36. language_code_prefix_re = re.compile(r'^/(\w+([@-]\w+)?)(/|$)')
  37. @receiver(setting_changed)
  38. def reset_cache(**kwargs):
  39. """
  40. Reset global state when LANGUAGES setting has been changed, as some
  41. languages should no longer be accepted.
  42. """
  43. if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'):
  44. check_for_language.cache_clear()
  45. get_languages.cache_clear()
  46. get_supported_language_variant.cache_clear()
  47. class DjangoTranslation(gettext_module.GNUTranslations):
  48. """
  49. Set up the GNUTranslations context with regard to output charset.
  50. This translation object will be constructed out of multiple GNUTranslations
  51. objects by merging their catalogs. It will construct an object for the
  52. requested language and add a fallback to the default language, if it's
  53. different from the requested language.
  54. """
  55. domain = 'django'
  56. def __init__(self, language, domain=None, localedirs=None):
  57. """Create a GNUTranslations() using many locale directories"""
  58. gettext_module.GNUTranslations.__init__(self)
  59. if domain is not None:
  60. self.domain = domain
  61. self.__language = language
  62. self.__to_language = to_language(language)
  63. self.__locale = to_locale(language)
  64. self._catalog = None
  65. # If a language doesn't have a catalog, use the Germanic default for
  66. # pluralization: anything except one is pluralized.
  67. self.plural = lambda n: int(n != 1)
  68. if self.domain == 'django':
  69. if localedirs is not None:
  70. # A module-level cache is used for caching 'django' translations
  71. warnings.warn("localedirs is ignored when domain is 'django'.", RuntimeWarning)
  72. localedirs = None
  73. self._init_translation_catalog()
  74. if localedirs:
  75. for localedir in localedirs:
  76. translation = self._new_gnu_trans(localedir)
  77. self.merge(translation)
  78. else:
  79. self._add_installed_apps_translations()
  80. self._add_local_translations()
  81. if self.__language == settings.LANGUAGE_CODE and self.domain == 'django' and self._catalog is None:
  82. # default lang should have at least one translation file available.
  83. raise OSError('No translation files found for default language %s.' % settings.LANGUAGE_CODE)
  84. self._add_fallback(localedirs)
  85. if self._catalog is None:
  86. # No catalogs found for this language, set an empty catalog.
  87. self._catalog = {}
  88. def __repr__(self):
  89. return "<DjangoTranslation lang:%s>" % self.__language
  90. def _new_gnu_trans(self, localedir, use_null_fallback=True):
  91. """
  92. Return a mergeable gettext.GNUTranslations instance.
  93. A convenience wrapper. By default gettext uses 'fallback=False'.
  94. Using param `use_null_fallback` to avoid confusion with any other
  95. references to 'fallback'.
  96. """
  97. return gettext_module.translation(
  98. domain=self.domain,
  99. localedir=localedir,
  100. languages=[self.__locale],
  101. fallback=use_null_fallback,
  102. )
  103. def _init_translation_catalog(self):
  104. """Create a base catalog using global django translations."""
  105. settingsfile = sys.modules[settings.__module__].__file__
  106. localedir = os.path.join(os.path.dirname(settingsfile), 'locale')
  107. translation = self._new_gnu_trans(localedir)
  108. self.merge(translation)
  109. def _add_installed_apps_translations(self):
  110. """Merge translations from each installed app."""
  111. try:
  112. app_configs = reversed(list(apps.get_app_configs()))
  113. except AppRegistryNotReady:
  114. raise AppRegistryNotReady(
  115. "The translation infrastructure cannot be initialized before the "
  116. "apps registry is ready. Check that you don't make non-lazy "
  117. "gettext calls at import time.")
  118. for app_config in app_configs:
  119. localedir = os.path.join(app_config.path, 'locale')
  120. if os.path.exists(localedir):
  121. translation = self._new_gnu_trans(localedir)
  122. self.merge(translation)
  123. def _add_local_translations(self):
  124. """Merge translations defined in LOCALE_PATHS."""
  125. for localedir in reversed(settings.LOCALE_PATHS):
  126. translation = self._new_gnu_trans(localedir)
  127. self.merge(translation)
  128. def _add_fallback(self, localedirs=None):
  129. """Set the GNUTranslations() fallback with the default language."""
  130. # Don't set a fallback for the default language or any English variant
  131. # (as it's empty, so it'll ALWAYS fall back to the default language)
  132. if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'):
  133. return
  134. if self.domain == 'django':
  135. # Get from cache
  136. default_translation = translation(settings.LANGUAGE_CODE)
  137. else:
  138. default_translation = DjangoTranslation(
  139. settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs
  140. )
  141. self.add_fallback(default_translation)
  142. def merge(self, other):
  143. """Merge another translation into this catalog."""
  144. if not getattr(other, '_catalog', None):
  145. return # NullTranslations() has no _catalog
  146. if self._catalog is None:
  147. # Take plural and _info from first catalog found (generally Django's).
  148. self.plural = other.plural
  149. self._info = other._info.copy()
  150. self._catalog = other._catalog.copy()
  151. else:
  152. self._catalog.update(other._catalog)
  153. if other._fallback:
  154. self.add_fallback(other._fallback)
  155. def language(self):
  156. """Return the translation language."""
  157. return self.__language
  158. def to_language(self):
  159. """Return the translation language name."""
  160. return self.__to_language
  161. def translation(language):
  162. """
  163. Return a translation object in the default 'django' domain.
  164. """
  165. global _translations
  166. if language not in _translations:
  167. _translations[language] = DjangoTranslation(language)
  168. return _translations[language]
  169. def activate(language):
  170. """
  171. Fetch the translation object for a given language and install it as the
  172. current translation object for the current thread.
  173. """
  174. if not language:
  175. return
  176. _active.value = translation(language)
  177. def deactivate():
  178. """
  179. Uninstall the active translation object so that further _() calls resolve
  180. to the default translation object.
  181. """
  182. if hasattr(_active, "value"):
  183. del _active.value
  184. def deactivate_all():
  185. """
  186. Make the active translation object a NullTranslations() instance. This is
  187. useful when we want delayed translations to appear as the original string
  188. for some reason.
  189. """
  190. _active.value = gettext_module.NullTranslations()
  191. _active.value.to_language = lambda *args: None
  192. def get_language():
  193. """Return the currently selected language."""
  194. t = getattr(_active, "value", None)
  195. if t is not None:
  196. try:
  197. return t.to_language()
  198. except AttributeError:
  199. pass
  200. # If we don't have a real translation object, assume it's the default language.
  201. return settings.LANGUAGE_CODE
  202. def get_language_bidi():
  203. """
  204. Return selected language's BiDi layout.
  205. * False = left-to-right layout
  206. * True = right-to-left layout
  207. """
  208. lang = get_language()
  209. if lang is None:
  210. return False
  211. else:
  212. base_lang = get_language().split('-')[0]
  213. return base_lang in settings.LANGUAGES_BIDI
  214. def catalog():
  215. """
  216. Return the current active catalog for further processing.
  217. This can be used if you need to modify the catalog or want to access the
  218. whole message catalog instead of just translating one string.
  219. """
  220. global _default
  221. t = getattr(_active, "value", None)
  222. if t is not None:
  223. return t
  224. if _default is None:
  225. _default = translation(settings.LANGUAGE_CODE)
  226. return _default
  227. def gettext(message):
  228. """
  229. Translate the 'message' string. It uses the current thread to find the
  230. translation object to use. If no current translation is activated, the
  231. message will be run through the default translation object.
  232. """
  233. global _default
  234. eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
  235. if eol_message:
  236. _default = _default or translation(settings.LANGUAGE_CODE)
  237. translation_object = getattr(_active, "value", _default)
  238. result = translation_object.gettext(eol_message)
  239. else:
  240. # Return an empty value of the corresponding type if an empty message
  241. # is given, instead of metadata, which is the default gettext behavior.
  242. result = type(message)('')
  243. if isinstance(message, SafeData):
  244. return mark_safe(result)
  245. return result
  246. def pgettext(context, message):
  247. msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
  248. result = gettext(msg_with_ctxt)
  249. if CONTEXT_SEPARATOR in result:
  250. # Translation not found
  251. result = message
  252. elif isinstance(message, SafeData):
  253. result = mark_safe(result)
  254. return result
  255. def gettext_noop(message):
  256. """
  257. Mark strings for translation but don't translate them now. This can be
  258. used to store strings in global variables that should stay in the base
  259. language (because they might be used externally) and will be translated
  260. later.
  261. """
  262. return message
  263. def do_ntranslate(singular, plural, number, translation_function):
  264. global _default
  265. t = getattr(_active, "value", None)
  266. if t is not None:
  267. return getattr(t, translation_function)(singular, plural, number)
  268. if _default is None:
  269. _default = translation(settings.LANGUAGE_CODE)
  270. return getattr(_default, translation_function)(singular, plural, number)
  271. def ngettext(singular, plural, number):
  272. """
  273. Return a string of the translation of either the singular or plural,
  274. based on the number.
  275. """
  276. return do_ntranslate(singular, plural, number, 'ngettext')
  277. def npgettext(context, singular, plural, number):
  278. msgs_with_ctxt = ("%s%s%s" % (context, CONTEXT_SEPARATOR, singular),
  279. "%s%s%s" % (context, CONTEXT_SEPARATOR, plural),
  280. number)
  281. result = ngettext(*msgs_with_ctxt)
  282. if CONTEXT_SEPARATOR in result:
  283. # Translation not found
  284. result = ngettext(singular, plural, number)
  285. return result
  286. def all_locale_paths():
  287. """
  288. Return a list of paths to user-provides languages files.
  289. """
  290. globalpath = os.path.join(
  291. os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
  292. app_paths = []
  293. for app_config in apps.get_app_configs():
  294. locale_path = os.path.join(app_config.path, 'locale')
  295. if os.path.exists(locale_path):
  296. app_paths.append(locale_path)
  297. return [globalpath, *settings.LOCALE_PATHS, *app_paths]
  298. @functools.lru_cache(maxsize=1000)
  299. def check_for_language(lang_code):
  300. """
  301. Check whether there is a global language file for the given language
  302. code. This is used to decide whether a user-provided language is
  303. available.
  304. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  305. as the provided language codes are taken from the HTTP request. See also
  306. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  307. """
  308. # First, a quick check to make sure lang_code is well-formed (#21458)
  309. if lang_code is None or not language_code_re.search(lang_code):
  310. return False
  311. return any(
  312. gettext_module.find('django', path, [to_locale(lang_code)]) is not None
  313. for path in all_locale_paths()
  314. )
  315. @functools.lru_cache()
  316. def get_languages():
  317. """
  318. Cache of settings.LANGUAGES in a dictionary for easy lookups by key.
  319. """
  320. return dict(settings.LANGUAGES)
  321. @functools.lru_cache(maxsize=1000)
  322. def get_supported_language_variant(lang_code, strict=False):
  323. """
  324. Return the language code that's listed in supported languages, possibly
  325. selecting a more generic variant. Raise LookupError if nothing is found.
  326. If `strict` is False (the default), look for a country-specific variant
  327. when neither the language code nor its generic variant is found.
  328. lru_cache should have a maxsize to prevent from memory exhaustion attacks,
  329. as the provided language codes are taken from the HTTP request. See also
  330. <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
  331. """
  332. if lang_code:
  333. # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
  334. possible_lang_codes = [lang_code]
  335. try:
  336. possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
  337. except KeyError:
  338. pass
  339. generic_lang_code = lang_code.split('-')[0]
  340. possible_lang_codes.append(generic_lang_code)
  341. supported_lang_codes = get_languages()
  342. for code in possible_lang_codes:
  343. if code in supported_lang_codes and check_for_language(code):
  344. return code
  345. if not strict:
  346. # if fr-fr is not supported, try fr-ca.
  347. for supported_code in supported_lang_codes:
  348. if supported_code.startswith(generic_lang_code + '-'):
  349. return supported_code
  350. raise LookupError(lang_code)
  351. def get_language_from_path(path, strict=False):
  352. """
  353. Return the language code if there's a valid language code found in `path`.
  354. If `strict` is False (the default), look for a country-specific variant
  355. when neither the language code nor its generic variant is found.
  356. """
  357. regex_match = language_code_prefix_re.match(path)
  358. if not regex_match:
  359. return None
  360. lang_code = regex_match.group(1)
  361. try:
  362. return get_supported_language_variant(lang_code, strict=strict)
  363. except LookupError:
  364. return None
  365. def get_language_from_request(request, check_path=False):
  366. """
  367. Analyze the request to find what language the user wants the system to
  368. show. Only languages listed in settings.LANGUAGES are taken into account.
  369. If the user requests a sublanguage where we have a main language, we send
  370. out the main language.
  371. If check_path is True, the URL path prefix will be checked for a language
  372. code, otherwise this is skipped for backwards compatibility.
  373. """
  374. if check_path:
  375. lang_code = get_language_from_path(request.path_info)
  376. if lang_code is not None:
  377. return lang_code
  378. lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
  379. if lang_code is not None and lang_code in get_languages() and check_for_language(lang_code):
  380. return lang_code
  381. try:
  382. return get_supported_language_variant(lang_code)
  383. except LookupError:
  384. pass
  385. accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
  386. for accept_lang, unused in parse_accept_lang_header(accept):
  387. if accept_lang == '*':
  388. break
  389. if not language_code_re.search(accept_lang):
  390. continue
  391. try:
  392. return get_supported_language_variant(accept_lang)
  393. except LookupError:
  394. continue
  395. try:
  396. return get_supported_language_variant(settings.LANGUAGE_CODE)
  397. except LookupError:
  398. return settings.LANGUAGE_CODE
  399. @functools.lru_cache(maxsize=1000)
  400. def parse_accept_lang_header(lang_string):
  401. """
  402. Parse the lang_string, which is the body of an HTTP Accept-Language
  403. header, and return a tuple of (lang, q-value), ordered by 'q' values.
  404. Return an empty tuple if there are any format errors in lang_string.
  405. """
  406. result = []
  407. pieces = accept_language_re.split(lang_string.lower())
  408. if pieces[-1]:
  409. return ()
  410. for i in range(0, len(pieces) - 1, 3):
  411. first, lang, priority = pieces[i:i + 3]
  412. if first:
  413. return ()
  414. if priority:
  415. priority = float(priority)
  416. else:
  417. priority = 1.0
  418. result.append((lang, priority))
  419. result.sort(key=lambda k: k[1], reverse=True)
  420. return tuple(result)