support.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. # -*- coding: utf-8 -*-
  2. """
  3. babel.support
  4. ~~~~~~~~~~~~~
  5. Several classes and functions that help with integrating and using Babel
  6. in applications.
  7. .. note: the code in this module is not used by Babel itself
  8. :copyright: (c) 2013 by the Babel Team.
  9. :license: BSD, see LICENSE for more details.
  10. """
  11. import gettext
  12. import locale
  13. from babel.core import Locale
  14. from babel.dates import format_date, format_datetime, format_time, \
  15. format_timedelta
  16. from babel.numbers import format_number, format_decimal, format_currency, \
  17. format_percent, format_scientific
  18. from babel._compat import PY2, text_type, text_to_native
  19. class Format(object):
  20. """Wrapper class providing the various date and number formatting functions
  21. bound to a specific locale and time-zone.
  22. >>> from babel.util import UTC
  23. >>> from datetime import date
  24. >>> fmt = Format('en_US', UTC)
  25. >>> fmt.date(date(2007, 4, 1))
  26. u'Apr 1, 2007'
  27. >>> fmt.decimal(1.2345)
  28. u'1.234'
  29. """
  30. def __init__(self, locale, tzinfo=None):
  31. """Initialize the formatter.
  32. :param locale: the locale identifier or `Locale` instance
  33. :param tzinfo: the time-zone info (a `tzinfo` instance or `None`)
  34. """
  35. self.locale = Locale.parse(locale)
  36. self.tzinfo = tzinfo
  37. def date(self, date=None, format='medium'):
  38. """Return a date formatted according to the given pattern.
  39. >>> from datetime import date
  40. >>> fmt = Format('en_US')
  41. >>> fmt.date(date(2007, 4, 1))
  42. u'Apr 1, 2007'
  43. """
  44. return format_date(date, format, locale=self.locale)
  45. def datetime(self, datetime=None, format='medium'):
  46. """Return a date and time formatted according to the given pattern.
  47. >>> from datetime import datetime
  48. >>> from pytz import timezone
  49. >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
  50. >>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
  51. u'Apr 1, 2007, 11:30:00 AM'
  52. """
  53. return format_datetime(datetime, format, tzinfo=self.tzinfo,
  54. locale=self.locale)
  55. def time(self, time=None, format='medium'):
  56. """Return a time formatted according to the given pattern.
  57. >>> from datetime import datetime
  58. >>> from pytz import timezone
  59. >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
  60. >>> fmt.time(datetime(2007, 4, 1, 15, 30))
  61. u'11:30:00 AM'
  62. """
  63. return format_time(time, format, tzinfo=self.tzinfo, locale=self.locale)
  64. def timedelta(self, delta, granularity='second', threshold=.85,
  65. format='medium', add_direction=False):
  66. """Return a time delta according to the rules of the given locale.
  67. >>> from datetime import timedelta
  68. >>> fmt = Format('en_US')
  69. >>> fmt.timedelta(timedelta(weeks=11))
  70. u'3 months'
  71. """
  72. return format_timedelta(delta, granularity=granularity,
  73. threshold=threshold,
  74. format=format, add_direction=add_direction,
  75. locale=self.locale)
  76. def number(self, number):
  77. """Return an integer number formatted for the locale.
  78. >>> fmt = Format('en_US')
  79. >>> fmt.number(1099)
  80. u'1,099'
  81. """
  82. return format_number(number, locale=self.locale)
  83. def decimal(self, number, format=None):
  84. """Return a decimal number formatted for the locale.
  85. >>> fmt = Format('en_US')
  86. >>> fmt.decimal(1.2345)
  87. u'1.234'
  88. """
  89. return format_decimal(number, format, locale=self.locale)
  90. def currency(self, number, currency):
  91. """Return a number in the given currency formatted for the locale.
  92. """
  93. return format_currency(number, currency, locale=self.locale)
  94. def percent(self, number, format=None):
  95. """Return a number formatted as percentage for the locale.
  96. >>> fmt = Format('en_US')
  97. >>> fmt.percent(0.34)
  98. u'34%'
  99. """
  100. return format_percent(number, format, locale=self.locale)
  101. def scientific(self, number):
  102. """Return a number formatted using scientific notation for the locale.
  103. """
  104. return format_scientific(number, locale=self.locale)
  105. class LazyProxy(object):
  106. """Class for proxy objects that delegate to a specified function to evaluate
  107. the actual object.
  108. >>> def greeting(name='world'):
  109. ... return 'Hello, %s!' % name
  110. >>> lazy_greeting = LazyProxy(greeting, name='Joe')
  111. >>> print(lazy_greeting)
  112. Hello, Joe!
  113. >>> u' ' + lazy_greeting
  114. u' Hello, Joe!'
  115. >>> u'(%s)' % lazy_greeting
  116. u'(Hello, Joe!)'
  117. This can be used, for example, to implement lazy translation functions that
  118. delay the actual translation until the string is actually used. The
  119. rationale for such behavior is that the locale of the user may not always
  120. be available. In web applications, you only know the locale when processing
  121. a request.
  122. The proxy implementation attempts to be as complete as possible, so that
  123. the lazy objects should mostly work as expected, for example for sorting:
  124. >>> greetings = [
  125. ... LazyProxy(greeting, 'world'),
  126. ... LazyProxy(greeting, 'Joe'),
  127. ... LazyProxy(greeting, 'universe'),
  128. ... ]
  129. >>> greetings.sort()
  130. >>> for greeting in greetings:
  131. ... print(greeting)
  132. Hello, Joe!
  133. Hello, universe!
  134. Hello, world!
  135. """
  136. __slots__ = ['_func', '_args', '_kwargs', '_value', '_is_cache_enabled']
  137. def __init__(self, func, *args, **kwargs):
  138. is_cache_enabled = kwargs.pop('enable_cache', True)
  139. # Avoid triggering our own __setattr__ implementation
  140. object.__setattr__(self, '_func', func)
  141. object.__setattr__(self, '_args', args)
  142. object.__setattr__(self, '_kwargs', kwargs)
  143. object.__setattr__(self, '_is_cache_enabled', is_cache_enabled)
  144. object.__setattr__(self, '_value', None)
  145. @property
  146. def value(self):
  147. if self._value is None:
  148. value = self._func(*self._args, **self._kwargs)
  149. if not self._is_cache_enabled:
  150. return value
  151. object.__setattr__(self, '_value', value)
  152. return self._value
  153. def __contains__(self, key):
  154. return key in self.value
  155. def __nonzero__(self):
  156. return bool(self.value)
  157. def __dir__(self):
  158. return dir(self.value)
  159. def __iter__(self):
  160. return iter(self.value)
  161. def __len__(self):
  162. return len(self.value)
  163. def __str__(self):
  164. return str(self.value)
  165. def __unicode__(self):
  166. return unicode(self.value)
  167. def __add__(self, other):
  168. return self.value + other
  169. def __radd__(self, other):
  170. return other + self.value
  171. def __mod__(self, other):
  172. return self.value % other
  173. def __rmod__(self, other):
  174. return other % self.value
  175. def __mul__(self, other):
  176. return self.value * other
  177. def __rmul__(self, other):
  178. return other * self.value
  179. def __call__(self, *args, **kwargs):
  180. return self.value(*args, **kwargs)
  181. def __lt__(self, other):
  182. return self.value < other
  183. def __le__(self, other):
  184. return self.value <= other
  185. def __eq__(self, other):
  186. return self.value == other
  187. def __ne__(self, other):
  188. return self.value != other
  189. def __gt__(self, other):
  190. return self.value > other
  191. def __ge__(self, other):
  192. return self.value >= other
  193. def __delattr__(self, name):
  194. delattr(self.value, name)
  195. def __getattr__(self, name):
  196. return getattr(self.value, name)
  197. def __setattr__(self, name, value):
  198. setattr(self.value, name, value)
  199. def __delitem__(self, key):
  200. del self.value[key]
  201. def __getitem__(self, key):
  202. return self.value[key]
  203. def __setitem__(self, key, value):
  204. self.value[key] = value
  205. def __copy__(self):
  206. return LazyProxy(
  207. self._func,
  208. enable_cache=self._is_cache_enabled,
  209. *self._args,
  210. **self._kwargs
  211. )
  212. def __deepcopy__(self, memo):
  213. from copy import deepcopy
  214. return LazyProxy(
  215. deepcopy(self._func, memo),
  216. enable_cache=deepcopy(self._is_cache_enabled, memo),
  217. *deepcopy(self._args, memo),
  218. **deepcopy(self._kwargs, memo)
  219. )
  220. class NullTranslations(gettext.NullTranslations, object):
  221. DEFAULT_DOMAIN = None
  222. def __init__(self, fp=None):
  223. """Initialize a simple translations class which is not backed by a
  224. real catalog. Behaves similar to gettext.NullTranslations but also
  225. offers Babel's on *gettext methods (e.g. 'dgettext()').
  226. :param fp: a file-like object (ignored in this class)
  227. """
  228. # These attributes are set by gettext.NullTranslations when a catalog
  229. # is parsed (fp != None). Ensure that they are always present because
  230. # some *gettext methods (including '.gettext()') rely on the attributes.
  231. self._catalog = {}
  232. self.plural = lambda n: int(n != 1)
  233. super(NullTranslations, self).__init__(fp=fp)
  234. self.files = list(filter(None, [getattr(fp, 'name', None)]))
  235. self.domain = self.DEFAULT_DOMAIN
  236. self._domains = {}
  237. def dgettext(self, domain, message):
  238. """Like ``gettext()``, but look the message up in the specified
  239. domain.
  240. """
  241. return self._domains.get(domain, self).gettext(message)
  242. def ldgettext(self, domain, message):
  243. """Like ``lgettext()``, but look the message up in the specified
  244. domain.
  245. """
  246. return self._domains.get(domain, self).lgettext(message)
  247. def udgettext(self, domain, message):
  248. """Like ``ugettext()``, but look the message up in the specified
  249. domain.
  250. """
  251. return self._domains.get(domain, self).ugettext(message)
  252. # backward compatibility with 0.9
  253. dugettext = udgettext
  254. def dngettext(self, domain, singular, plural, num):
  255. """Like ``ngettext()``, but look the message up in the specified
  256. domain.
  257. """
  258. return self._domains.get(domain, self).ngettext(singular, plural, num)
  259. def ldngettext(self, domain, singular, plural, num):
  260. """Like ``lngettext()``, but look the message up in the specified
  261. domain.
  262. """
  263. return self._domains.get(domain, self).lngettext(singular, plural, num)
  264. def udngettext(self, domain, singular, plural, num):
  265. """Like ``ungettext()`` but look the message up in the specified
  266. domain.
  267. """
  268. return self._domains.get(domain, self).ungettext(singular, plural, num)
  269. # backward compatibility with 0.9
  270. dungettext = udngettext
  271. # Most of the downwards code, until it get's included in stdlib, from:
  272. # http://bugs.python.org/file10036/gettext-pgettext.patch
  273. #
  274. # The encoding of a msgctxt and a msgid in a .mo file is
  275. # msgctxt + "\x04" + msgid (gettext version >= 0.15)
  276. CONTEXT_ENCODING = '%s\x04%s'
  277. def pgettext(self, context, message):
  278. """Look up the `context` and `message` id in the catalog and return the
  279. corresponding message string, as an 8-bit string encoded with the
  280. catalog's charset encoding, if known. If there is no entry in the
  281. catalog for the `message` id and `context` , and a fallback has been
  282. set, the look up is forwarded to the fallback's ``pgettext()``
  283. method. Otherwise, the `message` id is returned.
  284. """
  285. ctxt_msg_id = self.CONTEXT_ENCODING % (context, message)
  286. missing = object()
  287. tmsg = self._catalog.get(ctxt_msg_id, missing)
  288. if tmsg is missing:
  289. if self._fallback:
  290. return self._fallback.pgettext(context, message)
  291. return message
  292. # Encode the Unicode tmsg back to an 8-bit string, if possible
  293. if self._output_charset:
  294. return text_to_native(tmsg, self._output_charset)
  295. elif self._charset:
  296. return text_to_native(tmsg, self._charset)
  297. return tmsg
  298. def lpgettext(self, context, message):
  299. """Equivalent to ``pgettext()``, but the translation is returned in the
  300. preferred system encoding, if no other encoding was explicitly set with
  301. ``bind_textdomain_codeset()``.
  302. """
  303. ctxt_msg_id = self.CONTEXT_ENCODING % (context, message)
  304. missing = object()
  305. tmsg = self._catalog.get(ctxt_msg_id, missing)
  306. if tmsg is missing:
  307. if self._fallback:
  308. return self._fallback.lpgettext(context, message)
  309. return message
  310. if self._output_charset:
  311. return tmsg.encode(self._output_charset)
  312. return tmsg.encode(locale.getpreferredencoding())
  313. def npgettext(self, context, singular, plural, num):
  314. """Do a plural-forms lookup of a message id. `singular` is used as the
  315. message id for purposes of lookup in the catalog, while `num` is used to
  316. determine which plural form to use. The returned message string is an
  317. 8-bit string encoded with the catalog's charset encoding, if known.
  318. If the message id for `context` is not found in the catalog, and a
  319. fallback is specified, the request is forwarded to the fallback's
  320. ``npgettext()`` method. Otherwise, when ``num`` is 1 ``singular`` is
  321. returned, and ``plural`` is returned in all other cases.
  322. """
  323. ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
  324. try:
  325. tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
  326. if self._output_charset:
  327. return text_to_native(tmsg, self._output_charset)
  328. elif self._charset:
  329. return text_to_native(tmsg, self._charset)
  330. return tmsg
  331. except KeyError:
  332. if self._fallback:
  333. return self._fallback.npgettext(context, singular, plural, num)
  334. if num == 1:
  335. return singular
  336. else:
  337. return plural
  338. def lnpgettext(self, context, singular, plural, num):
  339. """Equivalent to ``npgettext()``, but the translation is returned in the
  340. preferred system encoding, if no other encoding was explicitly set with
  341. ``bind_textdomain_codeset()``.
  342. """
  343. ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
  344. try:
  345. tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
  346. if self._output_charset:
  347. return tmsg.encode(self._output_charset)
  348. return tmsg.encode(locale.getpreferredencoding())
  349. except KeyError:
  350. if self._fallback:
  351. return self._fallback.lnpgettext(context, singular, plural, num)
  352. if num == 1:
  353. return singular
  354. else:
  355. return plural
  356. def upgettext(self, context, message):
  357. """Look up the `context` and `message` id in the catalog and return the
  358. corresponding message string, as a Unicode string. If there is no entry
  359. in the catalog for the `message` id and `context`, and a fallback has
  360. been set, the look up is forwarded to the fallback's ``upgettext()``
  361. method. Otherwise, the `message` id is returned.
  362. """
  363. ctxt_message_id = self.CONTEXT_ENCODING % (context, message)
  364. missing = object()
  365. tmsg = self._catalog.get(ctxt_message_id, missing)
  366. if tmsg is missing:
  367. if self._fallback:
  368. return self._fallback.upgettext(context, message)
  369. return text_type(message)
  370. return tmsg
  371. def unpgettext(self, context, singular, plural, num):
  372. """Do a plural-forms lookup of a message id. `singular` is used as the
  373. message id for purposes of lookup in the catalog, while `num` is used to
  374. determine which plural form to use. The returned message string is a
  375. Unicode string.
  376. If the message id for `context` is not found in the catalog, and a
  377. fallback is specified, the request is forwarded to the fallback's
  378. ``unpgettext()`` method. Otherwise, when `num` is 1 `singular` is
  379. returned, and `plural` is returned in all other cases.
  380. """
  381. ctxt_message_id = self.CONTEXT_ENCODING % (context, singular)
  382. try:
  383. tmsg = self._catalog[(ctxt_message_id, self.plural(num))]
  384. except KeyError:
  385. if self._fallback:
  386. return self._fallback.unpgettext(context, singular, plural, num)
  387. if num == 1:
  388. tmsg = text_type(singular)
  389. else:
  390. tmsg = text_type(plural)
  391. return tmsg
  392. def dpgettext(self, domain, context, message):
  393. """Like `pgettext()`, but look the message up in the specified
  394. `domain`.
  395. """
  396. return self._domains.get(domain, self).pgettext(context, message)
  397. def udpgettext(self, domain, context, message):
  398. """Like `upgettext()`, but look the message up in the specified
  399. `domain`.
  400. """
  401. return self._domains.get(domain, self).upgettext(context, message)
  402. # backward compatibility with 0.9
  403. dupgettext = udpgettext
  404. def ldpgettext(self, domain, context, message):
  405. """Equivalent to ``dpgettext()``, but the translation is returned in the
  406. preferred system encoding, if no other encoding was explicitly set with
  407. ``bind_textdomain_codeset()``.
  408. """
  409. return self._domains.get(domain, self).lpgettext(context, message)
  410. def dnpgettext(self, domain, context, singular, plural, num):
  411. """Like ``npgettext``, but look the message up in the specified
  412. `domain`.
  413. """
  414. return self._domains.get(domain, self).npgettext(context, singular,
  415. plural, num)
  416. def udnpgettext(self, domain, context, singular, plural, num):
  417. """Like ``unpgettext``, but look the message up in the specified
  418. `domain`.
  419. """
  420. return self._domains.get(domain, self).unpgettext(context, singular,
  421. plural, num)
  422. # backward compatibility with 0.9
  423. dunpgettext = udnpgettext
  424. def ldnpgettext(self, domain, context, singular, plural, num):
  425. """Equivalent to ``dnpgettext()``, but the translation is returned in
  426. the preferred system encoding, if no other encoding was explicitly set
  427. with ``bind_textdomain_codeset()``.
  428. """
  429. return self._domains.get(domain, self).lnpgettext(context, singular,
  430. plural, num)
  431. if not PY2:
  432. ugettext = gettext.NullTranslations.gettext
  433. ungettext = gettext.NullTranslations.ngettext
  434. class Translations(NullTranslations, gettext.GNUTranslations):
  435. """An extended translation catalog class."""
  436. DEFAULT_DOMAIN = 'messages'
  437. def __init__(self, fp=None, domain=None):
  438. """Initialize the translations catalog.
  439. :param fp: the file-like object the translation should be read from
  440. :param domain: the message domain (default: 'messages')
  441. """
  442. super(Translations, self).__init__(fp=fp)
  443. self.domain = domain or self.DEFAULT_DOMAIN
  444. if not PY2:
  445. ugettext = gettext.GNUTranslations.gettext
  446. ungettext = gettext.GNUTranslations.ngettext
  447. @classmethod
  448. def load(cls, dirname=None, locales=None, domain=None):
  449. """Load translations from the given directory.
  450. :param dirname: the directory containing the ``MO`` files
  451. :param locales: the list of locales in order of preference (items in
  452. this list can be either `Locale` objects or locale
  453. strings)
  454. :param domain: the message domain (default: 'messages')
  455. """
  456. if locales is not None:
  457. if not isinstance(locales, (list, tuple)):
  458. locales = [locales]
  459. locales = [str(locale) for locale in locales]
  460. if not domain:
  461. domain = cls.DEFAULT_DOMAIN
  462. filename = gettext.find(domain, dirname, locales)
  463. if not filename:
  464. return NullTranslations()
  465. with open(filename, 'rb') as fp:
  466. return cls(fp=fp, domain=domain)
  467. def __repr__(self):
  468. return '<%s: "%s">' % (type(self).__name__,
  469. self._info.get('project-id-version'))
  470. def add(self, translations, merge=True):
  471. """Add the given translations to the catalog.
  472. If the domain of the translations is different than that of the
  473. current catalog, they are added as a catalog that is only accessible
  474. by the various ``d*gettext`` functions.
  475. :param translations: the `Translations` instance with the messages to
  476. add
  477. :param merge: whether translations for message domains that have
  478. already been added should be merged with the existing
  479. translations
  480. """
  481. domain = getattr(translations, 'domain', self.DEFAULT_DOMAIN)
  482. if merge and domain == self.domain:
  483. return self.merge(translations)
  484. existing = self._domains.get(domain)
  485. if merge and existing is not None:
  486. existing.merge(translations)
  487. else:
  488. translations.add_fallback(self)
  489. self._domains[domain] = translations
  490. return self
  491. def merge(self, translations):
  492. """Merge the given translations into the catalog.
  493. Message translations in the specified catalog override any messages
  494. with the same identifier in the existing catalog.
  495. :param translations: the `Translations` instance with the messages to
  496. merge
  497. """
  498. if isinstance(translations, gettext.GNUTranslations):
  499. self._catalog.update(translations._catalog)
  500. if isinstance(translations, Translations):
  501. self.files.extend(translations.files)
  502. return self