__init__.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. """
  2. Internationalization support.
  3. """
  4. from contextlib import ContextDecorator
  5. from decimal import ROUND_UP, Decimal
  6. from django.utils.autoreload import autoreload_started, file_changed
  7. from django.utils.functional import lazy
  8. from django.utils.regex_helper import _lazy_re_compile
  9. __all__ = [
  10. "activate",
  11. "deactivate",
  12. "override",
  13. "deactivate_all",
  14. "get_language",
  15. "get_language_from_request",
  16. "get_language_info",
  17. "get_language_bidi",
  18. "check_for_language",
  19. "to_language",
  20. "to_locale",
  21. "templatize",
  22. "gettext",
  23. "gettext_lazy",
  24. "gettext_noop",
  25. "ngettext",
  26. "ngettext_lazy",
  27. "pgettext",
  28. "pgettext_lazy",
  29. "npgettext",
  30. "npgettext_lazy",
  31. ]
  32. class TranslatorCommentWarning(SyntaxWarning):
  33. pass
  34. # Here be dragons, so a short explanation of the logic won't hurt:
  35. # We are trying to solve two problems: (1) access settings, in particular
  36. # settings.USE_I18N, as late as possible, so that modules can be imported
  37. # without having to first configure Django, and (2) if some other code creates
  38. # a reference to one of these functions, don't break that reference when we
  39. # replace the functions with their real counterparts (once we do access the
  40. # settings).
  41. class Trans:
  42. """
  43. The purpose of this class is to store the actual translation function upon
  44. receiving the first call to that function. After this is done, changes to
  45. USE_I18N will have no effect to which function is served upon request. If
  46. your tests rely on changing USE_I18N, you can delete all the functions
  47. from _trans.__dict__.
  48. Note that storing the function with setattr will have a noticeable
  49. performance effect, as access to the function goes the normal path,
  50. instead of using __getattr__.
  51. """
  52. def __getattr__(self, real_name):
  53. from django.conf import settings
  54. if settings.USE_I18N:
  55. from django.utils.translation import trans_real as trans
  56. from django.utils.translation.reloader import (
  57. translation_file_changed,
  58. watch_for_translation_changes,
  59. )
  60. autoreload_started.connect(
  61. watch_for_translation_changes, dispatch_uid="translation_file_changed"
  62. )
  63. file_changed.connect(
  64. translation_file_changed, dispatch_uid="translation_file_changed"
  65. )
  66. else:
  67. from django.utils.translation import trans_null as trans
  68. setattr(self, real_name, getattr(trans, real_name))
  69. return getattr(trans, real_name)
  70. _trans = Trans()
  71. # The Trans class is no more needed, so remove it from the namespace.
  72. del Trans
  73. def gettext_noop(message):
  74. return _trans.gettext_noop(message)
  75. def gettext(message):
  76. return _trans.gettext(message)
  77. def ngettext(singular, plural, number):
  78. return _trans.ngettext(singular, plural, number)
  79. def pgettext(context, message):
  80. return _trans.pgettext(context, message)
  81. def npgettext(context, singular, plural, number):
  82. return _trans.npgettext(context, singular, plural, number)
  83. gettext_lazy = lazy(gettext, str)
  84. pgettext_lazy = lazy(pgettext, str)
  85. def lazy_number(func, resultclass, number=None, **kwargs):
  86. if isinstance(number, int):
  87. kwargs["number"] = number
  88. proxy = lazy(func, resultclass)(**kwargs)
  89. else:
  90. original_kwargs = kwargs.copy()
  91. class NumberAwareString(resultclass):
  92. def __bool__(self):
  93. return bool(kwargs["singular"])
  94. def _get_number_value(self, values):
  95. try:
  96. return values[number]
  97. except KeyError:
  98. raise KeyError(
  99. "Your dictionary lacks key '%s'. Please provide "
  100. "it, because it is required to determine whether "
  101. "string is singular or plural." % number
  102. )
  103. def _translate(self, number_value):
  104. kwargs["number"] = number_value
  105. return func(**kwargs)
  106. def format(self, *args, **kwargs):
  107. number_value = (
  108. self._get_number_value(kwargs) if kwargs and number else args[0]
  109. )
  110. return self._translate(number_value).format(*args, **kwargs)
  111. def __mod__(self, rhs):
  112. if isinstance(rhs, dict) and number:
  113. number_value = self._get_number_value(rhs)
  114. else:
  115. number_value = rhs
  116. translated = self._translate(number_value)
  117. try:
  118. translated %= rhs
  119. except TypeError:
  120. # String doesn't contain a placeholder for the number.
  121. pass
  122. return translated
  123. proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
  124. proxy.__reduce__ = lambda: (
  125. _lazy_number_unpickle,
  126. (func, resultclass, number, original_kwargs),
  127. )
  128. return proxy
  129. def _lazy_number_unpickle(func, resultclass, number, kwargs):
  130. return lazy_number(func, resultclass, number=number, **kwargs)
  131. def ngettext_lazy(singular, plural, number=None):
  132. return lazy_number(ngettext, str, singular=singular, plural=plural, number=number)
  133. def npgettext_lazy(context, singular, plural, number=None):
  134. return lazy_number(
  135. npgettext, str, context=context, singular=singular, plural=plural, number=number
  136. )
  137. def activate(language):
  138. return _trans.activate(language)
  139. def deactivate():
  140. return _trans.deactivate()
  141. class override(ContextDecorator):
  142. def __init__(self, language, deactivate=False):
  143. self.language = language
  144. self.deactivate = deactivate
  145. def __enter__(self):
  146. self.old_language = get_language()
  147. if self.language is not None:
  148. activate(self.language)
  149. else:
  150. deactivate_all()
  151. def __exit__(self, exc_type, exc_value, traceback):
  152. if self.old_language is None:
  153. deactivate_all()
  154. elif self.deactivate:
  155. deactivate()
  156. else:
  157. activate(self.old_language)
  158. def get_language():
  159. return _trans.get_language()
  160. def get_language_bidi():
  161. return _trans.get_language_bidi()
  162. def check_for_language(lang_code):
  163. return _trans.check_for_language(lang_code)
  164. def to_language(locale):
  165. """Turn a locale name (en_US) into a language name (en-us)."""
  166. p = locale.find("_")
  167. if p >= 0:
  168. return locale[:p].lower() + "-" + locale[p + 1 :].lower()
  169. else:
  170. return locale.lower()
  171. def to_locale(language):
  172. """Turn a language name (en-us) into a locale name (en_US)."""
  173. lang, _, country = language.lower().partition("-")
  174. if not country:
  175. return language[:3].lower() + language[3:]
  176. # A language with > 2 characters after the dash only has its first
  177. # character after the dash capitalized; e.g. sr-latn becomes sr_Latn.
  178. # A language with 2 characters after the dash has both characters
  179. # capitalized; e.g. en-us becomes en_US.
  180. country, _, tail = country.partition("-")
  181. country = country.title() if len(country) > 2 else country.upper()
  182. if tail:
  183. country += "-" + tail
  184. return lang + "_" + country
  185. def get_language_from_request(request, check_path=False):
  186. return _trans.get_language_from_request(request, check_path)
  187. def get_language_from_path(path):
  188. return _trans.get_language_from_path(path)
  189. def get_supported_language_variant(lang_code, *, strict=False):
  190. return _trans.get_supported_language_variant(lang_code, strict)
  191. def templatize(src, **kwargs):
  192. from .template import templatize
  193. return templatize(src, **kwargs)
  194. def deactivate_all():
  195. return _trans.deactivate_all()
  196. def get_language_info(lang_code):
  197. from django.conf.locale import LANG_INFO
  198. try:
  199. lang_info = LANG_INFO[lang_code]
  200. if "fallback" in lang_info and "name" not in lang_info:
  201. info = get_language_info(lang_info["fallback"][0])
  202. else:
  203. info = lang_info
  204. except KeyError:
  205. if "-" not in lang_code:
  206. raise KeyError("Unknown language code %s." % lang_code)
  207. generic_lang_code = lang_code.split("-")[0]
  208. try:
  209. info = LANG_INFO[generic_lang_code]
  210. except KeyError:
  211. raise KeyError(
  212. "Unknown language code %s and %s." % (lang_code, generic_lang_code)
  213. )
  214. if info:
  215. info["name_translated"] = gettext_lazy(info["name"])
  216. return info
  217. trim_whitespace_re = _lazy_re_compile(r"\s*\n\s*")
  218. def trim_whitespace(s):
  219. return trim_whitespace_re.sub(" ", s.strip())
  220. def round_away_from_one(value):
  221. return int(Decimal(value - 1).quantize(Decimal("0"), rounding=ROUND_UP)) + 1