PageRenderTime 63ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/utils/translation/trans_real.py

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