PageRenderTime 61ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/django/utils/translation/trans_real.py

https://github.com/insane/django
Python | 676 lines | 608 code | 21 blank | 47 comment | 24 complexity | 70959493e7ee7a868e4fb0863af565be MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """Translation helper functions."""
  2. from __future__ import unicode_literals
  3. import locale
  4. import os
  5. import re
  6. import sys
  7. import gettext as gettext_module
  8. from threading import local
  9. import warnings
  10. from django.utils.importlib import import_module
  11. from django.utils.datastructures import SortedDict
  12. from django.utils.encoding import force_str, force_text
  13. from django.utils.functional import memoize
  14. from django.utils._os import upath
  15. from django.utils.safestring import mark_safe, SafeData
  16. from django.utils import six
  17. from django.utils.six import StringIO
  18. from django.utils.translation import TranslatorCommentWarning
  19. # Translations are cached in a dictionary for every language+app tuple.
  20. # The active translations are stored by threadid to make them thread local.
  21. _translations = {}
  22. _active = local()
  23. # The default translation is based on the settings file.
  24. _default = None
  25. # This is a cache for normalized accept-header languages to prevent multiple
  26. # file lookups when checking the same locale on repeated requests.
  27. _accepted = {}
  28. _checked_languages = {}
  29. # magic gettext number to separate context from message
  30. CONTEXT_SEPARATOR = "\x04"
  31. # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9
  32. # and RFC 3066, section 2.1
  33. accept_language_re = re.compile(r'''
  34. ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # "en", "en-au", "x-y-z", "es-419", "*"
  35. (?:\s*;\s*q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8"
  36. (?:\s*,\s*|$) # Multiple accepts per header.
  37. ''', re.VERBOSE)
  38. language_code_prefix_re = re.compile(r'^/([\w-]+)(/|$)')
  39. def to_locale(language, to_lower=False):
  40. """
  41. Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
  42. True, the last component is lower-cased (en_us).
  43. """
  44. p = language.find('-')
  45. if p >= 0:
  46. if to_lower:
  47. return language[:p].lower()+'_'+language[p+1:].lower()
  48. else:
  49. # Get correct locale for sr-latn
  50. if len(language[p+1:]) > 2:
  51. return language[:p].lower()+'_'+language[p+1].upper()+language[p+2:].lower()
  52. return language[:p].lower()+'_'+language[p+1:].upper()
  53. else:
  54. return language.lower()
  55. def to_language(locale):
  56. """Turns a locale name (en_US) into a language name (en-us)."""
  57. p = locale.find('_')
  58. if p >= 0:
  59. return locale[:p].lower()+'-'+locale[p+1:].lower()
  60. else:
  61. return locale.lower()
  62. class DjangoTranslation(gettext_module.GNUTranslations):
  63. """
  64. This class sets up the GNUTranslations context with regard to output
  65. charset.
  66. """
  67. def __init__(self, *args, **kw):
  68. gettext_module.GNUTranslations.__init__(self, *args, **kw)
  69. self.set_output_charset('utf-8')
  70. self.__language = '??'
  71. def merge(self, other):
  72. self._catalog.update(other._catalog)
  73. def set_language(self, language):
  74. self.__language = language
  75. self.__to_language = to_language(language)
  76. def language(self):
  77. return self.__language
  78. def to_language(self):
  79. return self.__to_language
  80. def __repr__(self):
  81. return "<DjangoTranslation lang:%s>" % self.__language
  82. def translation(language):
  83. """
  84. Returns a translation object.
  85. This translation object will be constructed out of multiple GNUTranslations
  86. objects by merging their catalogs. It will construct a object for the
  87. requested language and add a fallback to the default language, if it's
  88. different from the requested language.
  89. """
  90. global _translations
  91. t = _translations.get(language, None)
  92. if t is not None:
  93. return t
  94. from django.conf import settings
  95. globalpath = os.path.join(os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
  96. def _fetch(lang, fallback=None):
  97. global _translations
  98. res = _translations.get(lang, None)
  99. if res is not None:
  100. return res
  101. loc = to_locale(lang)
  102. def _translation(path):
  103. try:
  104. t = gettext_module.translation('django', path, [loc], DjangoTranslation)
  105. t.set_language(lang)
  106. return t
  107. except IOError:
  108. return None
  109. res = _translation(globalpath)
  110. # We want to ensure that, for example, "en-gb" and "en-us" don't share
  111. # the same translation object (thus, merging en-us with a local update
  112. # doesn't affect en-gb), even though they will both use the core "en"
  113. # translation. So we have to subvert Python's internal gettext caching.
  114. base_lang = lambda x: x.split('-', 1)[0]
  115. if base_lang(lang) in [base_lang(trans) for trans in list(_translations)]:
  116. res._info = res._info.copy()
  117. res._catalog = res._catalog.copy()
  118. def _merge(path):
  119. t = _translation(path)
  120. if t is not None:
  121. if res is None:
  122. return t
  123. else:
  124. res.merge(t)
  125. return res
  126. for appname in reversed(settings.INSTALLED_APPS):
  127. app = import_module(appname)
  128. apppath = os.path.join(os.path.dirname(upath(app.__file__)), 'locale')
  129. if os.path.isdir(apppath):
  130. res = _merge(apppath)
  131. for localepath in reversed(settings.LOCALE_PATHS):
  132. if os.path.isdir(localepath):
  133. res = _merge(localepath)
  134. if res is None:
  135. if fallback is not None:
  136. res = fallback
  137. else:
  138. return gettext_module.NullTranslations()
  139. _translations[lang] = res
  140. return res
  141. default_translation = _fetch(settings.LANGUAGE_CODE)
  142. current_translation = _fetch(language, fallback=default_translation)
  143. return current_translation
  144. def activate(language):
  145. """
  146. Fetches the translation object for a given tuple of application name and
  147. language and installs it as the current translation object for the current
  148. thread.
  149. """
  150. _active.value = translation(language)
  151. def deactivate():
  152. """
  153. Deinstalls the currently active translation object so that further _ calls
  154. will resolve against the default translation object, again.
  155. """
  156. if hasattr(_active, "value"):
  157. del _active.value
  158. def deactivate_all():
  159. """
  160. Makes the active translation object a NullTranslations() instance. This is
  161. useful when we want delayed translations to appear as the original string
  162. for some reason.
  163. """
  164. _active.value = gettext_module.NullTranslations()
  165. def get_language():
  166. """Returns the currently selected language."""
  167. t = getattr(_active, "value", None)
  168. if t is not None:
  169. try:
  170. return t.to_language()
  171. except AttributeError:
  172. pass
  173. # If we don't have a real translation object, assume it's the default language.
  174. from django.conf import settings
  175. return settings.LANGUAGE_CODE
  176. def get_language_bidi():
  177. """
  178. Returns selected language's BiDi layout.
  179. * False = left-to-right layout
  180. * True = right-to-left layout
  181. """
  182. from django.conf import settings
  183. base_lang = get_language().split('-')[0]
  184. return base_lang in settings.LANGUAGES_BIDI
  185. def catalog():
  186. """
  187. Returns the current active catalog for further processing.
  188. This can be used if you need to modify the catalog or want to access the
  189. whole message catalog instead of just translating one string.
  190. """
  191. global _default
  192. t = getattr(_active, "value", None)
  193. if t is not None:
  194. return t
  195. if _default is None:
  196. from django.conf import settings
  197. _default = translation(settings.LANGUAGE_CODE)
  198. return _default
  199. def do_translate(message, translation_function):
  200. """
  201. Translates 'message' using the given 'translation_function' name -- which
  202. will be either gettext or ugettext. It uses the current thread to find the
  203. translation object to use. If no current translation is activated, the
  204. message will be run through the default translation object.
  205. """
  206. global _default
  207. # str() is allowing a bytestring message to remain bytestring on Python 2
  208. eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))
  209. t = getattr(_active, "value", None)
  210. if t is not None:
  211. result = getattr(t, translation_function)(eol_message)
  212. else:
  213. if _default is None:
  214. from django.conf import settings
  215. _default = translation(settings.LANGUAGE_CODE)
  216. result = getattr(_default, translation_function)(eol_message)
  217. if isinstance(message, SafeData):
  218. return mark_safe(result)
  219. return result
  220. def gettext(message):
  221. """
  222. Returns a string of the translation of the message.
  223. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2.
  224. """
  225. return do_translate(message, 'gettext')
  226. if six.PY3:
  227. ugettext = gettext
  228. else:
  229. def ugettext(message):
  230. return do_translate(message, 'ugettext')
  231. def pgettext(context, message):
  232. msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
  233. result = ugettext(msg_with_ctxt)
  234. if CONTEXT_SEPARATOR in result:
  235. # Translation not found
  236. result = message
  237. return result
  238. def gettext_noop(message):
  239. """
  240. Marks strings for translation but doesn't translate them now. This can be
  241. used to store strings in global variables that should stay in the base
  242. language (because they might be used externally) and will be translated
  243. later.
  244. """
  245. return message
  246. def do_ntranslate(singular, plural, number, translation_function):
  247. global _default
  248. t = getattr(_active, "value", None)
  249. if t is not None:
  250. return getattr(t, translation_function)(singular, plural, number)
  251. if _default is None:
  252. from django.conf import settings
  253. _default = translation(settings.LANGUAGE_CODE)
  254. return getattr(_default, translation_function)(singular, plural, number)
  255. def ngettext(singular, plural, number):
  256. """
  257. Returns a string of the translation of either the singular or plural,
  258. based on the number.
  259. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2.
  260. """
  261. return do_ntranslate(singular, plural, number, 'ngettext')
  262. if six.PY3:
  263. ungettext = ngettext
  264. else:
  265. def ungettext(singular, plural, number):
  266. """
  267. Returns a unicode strings of the translation of either the singular or
  268. plural, based on the number.
  269. """
  270. return do_ntranslate(singular, plural, number, 'ungettext')
  271. def npgettext(context, singular, plural, number):
  272. msgs_with_ctxt = ("%s%s%s" % (context, CONTEXT_SEPARATOR, singular),
  273. "%s%s%s" % (context, CONTEXT_SEPARATOR, plural),
  274. number)
  275. result = ungettext(*msgs_with_ctxt)
  276. if CONTEXT_SEPARATOR in result:
  277. # Translation not found
  278. result = ungettext(singular, plural, number)
  279. return result
  280. def all_locale_paths():
  281. """
  282. Returns a list of paths to user-provides languages files.
  283. """
  284. from django.conf import settings
  285. globalpath = os.path.join(
  286. os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
  287. return [globalpath] + list(settings.LOCALE_PATHS)
  288. def check_for_language(lang_code):
  289. """
  290. Checks whether there is a global language file for the given language
  291. code. This is used to decide whether a user-provided language is
  292. available. This is only used for language codes from either the cookies
  293. or session and during format localization.
  294. """
  295. for path in all_locale_paths():
  296. if gettext_module.find('django', path, [to_locale(lang_code)]) is not None:
  297. return True
  298. return False
  299. check_for_language = memoize(check_for_language, _checked_languages, 1)
  300. def get_supported_language_variant(lang_code, supported=None, strict=False):
  301. """
  302. Returns the language-code that's listed in supported languages, possibly
  303. selecting a more generic variant. Raises LookupError if nothing found.
  304. If `strict` is False (the default), the function will look for an alternative
  305. country-specific variant when the currently checked is not found.
  306. """
  307. if supported is None:
  308. from django.conf import settings
  309. supported = SortedDict(settings.LANGUAGES)
  310. if lang_code:
  311. # if fr-CA is not supported, try fr-ca; if that fails, fallback to fr.
  312. generic_lang_code = lang_code.split('-')[0]
  313. variants = (lang_code, lang_code.lower(), generic_lang_code,
  314. generic_lang_code.lower())
  315. for code in variants:
  316. if code in supported and check_for_language(code):
  317. return code
  318. if not strict:
  319. # if fr-fr is not supported, try fr-ca.
  320. for supported_code in supported:
  321. if supported_code.startswith((generic_lang_code + '-',
  322. generic_lang_code.lower() + '-')):
  323. return supported_code
  324. raise LookupError(lang_code)
  325. def get_language_from_path(path, supported=None, strict=False):
  326. """
  327. Returns the language-code if there is a valid language-code
  328. found in the `path`.
  329. If `strict` is False (the default), the function will look for an alternative
  330. country-specific variant when the currently checked is not found.
  331. """
  332. if supported is None:
  333. from django.conf import settings
  334. supported = SortedDict(settings.LANGUAGES)
  335. regex_match = language_code_prefix_re.match(path)
  336. if not regex_match:
  337. return None
  338. lang_code = regex_match.group(1)
  339. try:
  340. return get_supported_language_variant(lang_code, supported, strict=strict)
  341. except LookupError:
  342. return None
  343. def get_language_from_request(request, check_path=False):
  344. """
  345. Analyzes the request to find what language the user wants the system to
  346. show. Only languages listed in settings.LANGUAGES are taken into account.
  347. If the user requests a sublanguage where we have a main language, we send
  348. out the main language.
  349. If check_path is True, the URL path prefix will be checked for a language
  350. code, otherwise this is skipped for backwards compatibility.
  351. """
  352. global _accepted
  353. from django.conf import settings
  354. supported = SortedDict(settings.LANGUAGES)
  355. if check_path:
  356. lang_code = get_language_from_path(request.path_info, supported)
  357. if lang_code is not None:
  358. return lang_code
  359. if hasattr(request, 'session'):
  360. lang_code = request.session.get('django_language', None)
  361. if lang_code in supported and lang_code is not None and check_for_language(lang_code):
  362. return lang_code
  363. lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
  364. try:
  365. return get_supported_language_variant(lang_code, supported)
  366. except LookupError:
  367. pass
  368. accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
  369. for accept_lang, unused in parse_accept_lang_header(accept):
  370. if accept_lang == '*':
  371. break
  372. # 'normalized' is the root name of the locale in POSIX format (which is
  373. # the format used for the directories holding the MO files).
  374. normalized = locale.locale_alias.get(to_locale(accept_lang, True))
  375. if not normalized:
  376. continue
  377. # Remove the default encoding from locale_alias.
  378. normalized = normalized.split('.')[0]
  379. if normalized in _accepted:
  380. # We've seen this locale before and have an MO file for it, so no
  381. # need to check again.
  382. return _accepted[normalized]
  383. try:
  384. accept_lang = get_supported_language_variant(accept_lang, supported)
  385. except LookupError:
  386. continue
  387. else:
  388. _accepted[normalized] = accept_lang
  389. return accept_lang
  390. try:
  391. return get_supported_language_variant(settings.LANGUAGE_CODE, supported)
  392. except LookupError:
  393. return settings.LANGUAGE_CODE
  394. dot_re = re.compile(r'\S')
  395. def blankout(src, char):
  396. """
  397. Changes every non-whitespace character to the given char.
  398. Used in the templatize function.
  399. """
  400. return dot_re.sub(char, src)
  401. context_re = re.compile(r"""^\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?'))\s*""")
  402. inline_re = re.compile(r"""^\s*trans\s+((?:"[^"]*?")|(?:'[^']*?'))(\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?')))?\s*""")
  403. block_re = re.compile(r"""^\s*blocktrans(\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?')))?(?:\s+|$)""")
  404. endblock_re = re.compile(r"""^\s*endblocktrans$""")
  405. plural_re = re.compile(r"""^\s*plural$""")
  406. constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?'))\)""")
  407. one_percent_re = re.compile(r"""(?<!%)%(?!%)""")
  408. def templatize(src, origin=None):
  409. """
  410. Turns a Django template into something that is understood by xgettext. It
  411. does so by translating the Django translation tags into standard gettext
  412. function invocations.
  413. """
  414. from django.conf import settings
  415. from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK,
  416. TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)
  417. src = force_text(src, settings.FILE_CHARSET)
  418. out = StringIO()
  419. message_context = None
  420. intrans = False
  421. inplural = False
  422. singular = []
  423. plural = []
  424. incomment = False
  425. comment = []
  426. lineno_comment_map = {}
  427. comment_lineno_cache = None
  428. for t in Lexer(src, origin).tokenize():
  429. if incomment:
  430. if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
  431. content = ''.join(comment)
  432. translators_comment_start = None
  433. for lineno, line in enumerate(content.splitlines(True)):
  434. if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
  435. translators_comment_start = lineno
  436. for lineno, line in enumerate(content.splitlines(True)):
  437. if translators_comment_start is not None and lineno >= translators_comment_start:
  438. out.write(' # %s' % line)
  439. else:
  440. out.write(' #\n')
  441. incomment = False
  442. comment = []
  443. else:
  444. comment.append(t.contents)
  445. elif intrans:
  446. if t.token_type == TOKEN_BLOCK:
  447. endbmatch = endblock_re.match(t.contents)
  448. pluralmatch = plural_re.match(t.contents)
  449. if endbmatch:
  450. if inplural:
  451. if message_context:
  452. out.write(' npgettext(%r, %r, %r,count) ' % (message_context, ''.join(singular), ''.join(plural)))
  453. else:
  454. out.write(' ngettext(%r, %r, count) ' % (''.join(singular), ''.join(plural)))
  455. for part in singular:
  456. out.write(blankout(part, 'S'))
  457. for part in plural:
  458. out.write(blankout(part, 'P'))
  459. else:
  460. if message_context:
  461. out.write(' pgettext(%r, %r) ' % (message_context, ''.join(singular)))
  462. else:
  463. out.write(' gettext(%r) ' % ''.join(singular))
  464. for part in singular:
  465. out.write(blankout(part, 'S'))
  466. message_context = None
  467. intrans = False
  468. inplural = False
  469. singular = []
  470. plural = []
  471. elif pluralmatch:
  472. inplural = True
  473. else:
  474. filemsg = ''
  475. if origin:
  476. filemsg = 'file %s, ' % origin
  477. raise SyntaxError("Translation blocks must not include other block tags: %s (%sline %d)" % (t.contents, filemsg, t.lineno))
  478. elif t.token_type == TOKEN_VAR:
  479. if inplural:
  480. plural.append('%%(%s)s' % t.contents)
  481. else:
  482. singular.append('%%(%s)s' % t.contents)
  483. elif t.token_type == TOKEN_TEXT:
  484. contents = one_percent_re.sub('%%', t.contents)
  485. if inplural:
  486. plural.append(contents)
  487. else:
  488. singular.append(contents)
  489. else:
  490. # Handle comment tokens (`{# ... #}`) plus other constructs on
  491. # the same line:
  492. if comment_lineno_cache is not None:
  493. cur_lineno = t.lineno + t.contents.count('\n')
  494. if comment_lineno_cache == cur_lineno:
  495. if t.token_type != TOKEN_COMMENT:
  496. for c in lineno_comment_map[comment_lineno_cache]:
  497. filemsg = ''
  498. if origin:
  499. filemsg = 'file %s, ' % origin
  500. warn_msg = ("The translator-targeted comment '%s' "
  501. "(%sline %d) was ignored, because it wasn't the last item "
  502. "on the line.") % (c, filemsg, comment_lineno_cache)
  503. warnings.warn(warn_msg, TranslatorCommentWarning)
  504. lineno_comment_map[comment_lineno_cache] = []
  505. else:
  506. out.write('# %s' % ' | '.join(lineno_comment_map[comment_lineno_cache]))
  507. comment_lineno_cache = None
  508. if t.token_type == TOKEN_BLOCK:
  509. imatch = inline_re.match(t.contents)
  510. bmatch = block_re.match(t.contents)
  511. cmatches = constant_re.findall(t.contents)
  512. if imatch:
  513. g = imatch.group(1)
  514. if g[0] == '"':
  515. g = g.strip('"')
  516. elif g[0] == "'":
  517. g = g.strip("'")
  518. g = one_percent_re.sub('%%', g)
  519. if imatch.group(2):
  520. # A context is provided
  521. context_match = context_re.match(imatch.group(2))
  522. message_context = context_match.group(1)
  523. if message_context[0] == '"':
  524. message_context = message_context.strip('"')
  525. elif message_context[0] == "'":
  526. message_context = message_context.strip("'")
  527. out.write(' pgettext(%r, %r) ' % (message_context, g))
  528. message_context = None
  529. else:
  530. out.write(' gettext(%r) ' % g)
  531. elif bmatch:
  532. for fmatch in constant_re.findall(t.contents):
  533. out.write(' _(%s) ' % fmatch)
  534. if bmatch.group(1):
  535. # A context is provided
  536. context_match = context_re.match(bmatch.group(1))
  537. message_context = context_match.group(1)
  538. if message_context[0] == '"':
  539. message_context = message_context.strip('"')
  540. elif message_context[0] == "'":
  541. message_context = message_context.strip("'")
  542. intrans = True
  543. inplural = False
  544. singular = []
  545. plural = []
  546. elif cmatches:
  547. for cmatch in cmatches:
  548. out.write(' _(%s) ' % cmatch)
  549. elif t.contents == 'comment':
  550. incomment = True
  551. else:
  552. out.write(blankout(t.contents, 'B'))
  553. elif t.token_type == TOKEN_VAR:
  554. parts = t.contents.split('|')
  555. cmatch = constant_re.match(parts[0])
  556. if cmatch:
  557. out.write(' _(%s) ' % cmatch.group(1))
  558. for p in parts[1:]:
  559. if p.find(':_(') >= 0:
  560. out.write(' %s ' % p.split(':',1)[1])
  561. else:
  562. out.write(blankout(p, 'F'))
  563. elif t.token_type == TOKEN_COMMENT:
  564. if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
  565. lineno_comment_map.setdefault(t.lineno,
  566. []).append(t.contents)
  567. comment_lineno_cache = t.lineno
  568. else:
  569. out.write(blankout(t.contents, 'X'))
  570. return force_str(out.getvalue())
  571. def parse_accept_lang_header(lang_string):
  572. """
  573. Parses the lang_string, which is the body of an HTTP Accept-Language
  574. header, and returns a list of (lang, q-value), ordered by 'q' values.
  575. Any format errors in lang_string results in an empty list being returned.
  576. """
  577. result = []
  578. pieces = accept_language_re.split(lang_string)
  579. if pieces[-1]:
  580. return []
  581. for i in range(0, len(pieces) - 1, 3):
  582. first, lang, priority = pieces[i : i + 3]
  583. if first:
  584. return []
  585. if priority:
  586. priority = float(priority)
  587. if not priority: # if priority is 0.0 at this point make it 1.0
  588. priority = 1.0
  589. result.append((lang, priority))
  590. result.sort(key=lambda k: k[1], reverse=True)
  591. return result