You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

trans_real.py 18KB

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