__init__.py 11 KB

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