You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

760 lines
28 KiB

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