PageRenderTime 42ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/django/utils/translation/trans_real.py

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