trans_real.py 27 KB

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