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

/google/appengine/_internal/django/utils/translation/trans_real.py

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