support.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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-2021 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='long', 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', '_attribute_error']
  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. object.__setattr__(self, '_attribute_error', None)
  146. @property
  147. def value(self):
  148. if self._value is None:
  149. try:
  150. value = self._func(*self._args, **self._kwargs)
  151. except AttributeError as error:
  152. object.__setattr__(self, '_attribute_error', error)
  153. raise
  154. if not self._is_cache_enabled:
  155. return value
  156. object.__setattr__(self, '_value', value)
  157. return self._value
  158. def __contains__(self, key):
  159. return key in self.value
  160. def __nonzero__(self):
  161. return bool(self.value)
  162. def __dir__(self):
  163. return dir(self.value)
  164. def __iter__(self):
  165. return iter(self.value)
  166. def __len__(self):
  167. return len(self.value)
  168. def __str__(self):
  169. return str(self.value)
  170. def __unicode__(self):
  171. return unicode(self.value)
  172. def __add__(self, other):
  173. return self.value + other
  174. def __radd__(self, other):
  175. return other + self.value
  176. def __mod__(self, other):
  177. return self.value % other
  178. def __rmod__(self, other):
  179. return other % self.value
  180. def __mul__(self, other):
  181. return self.value * other
  182. def __rmul__(self, other):
  183. return other * self.value
  184. def __call__(self, *args, **kwargs):
  185. return self.value(*args, **kwargs)
  186. def __lt__(self, other):
  187. return self.value < other
  188. def __le__(self, other):
  189. return self.value <= other
  190. def __eq__(self, other):
  191. return self.value == other
  192. def __ne__(self, other):
  193. return self.value != other
  194. def __gt__(self, other):
  195. return self.value > other
  196. def __ge__(self, other):
  197. return self.value >= other
  198. def __delattr__(self, name):
  199. delattr(self.value, name)
  200. def __getattr__(self, name):
  201. if self._attribute_error is not None:
  202. raise self._attribute_error
  203. return getattr(self.value, name)
  204. def __setattr__(self, name, value):
  205. setattr(self.value, name, value)
  206. def __delitem__(self, key):
  207. del self.value[key]
  208. def __getitem__(self, key):
  209. return self.value[key]
  210. def __setitem__(self, key, value):
  211. self.value[key] = value
  212. def __copy__(self):
  213. return LazyProxy(
  214. self._func,
  215. enable_cache=self._is_cache_enabled,
  216. *self._args,
  217. **self._kwargs
  218. )
  219. def __deepcopy__(self, memo):
  220. from copy import deepcopy
  221. return LazyProxy(
  222. deepcopy(self._func, memo),
  223. enable_cache=deepcopy(self._is_cache_enabled, memo),
  224. *deepcopy(self._args, memo),
  225. **deepcopy(self._kwargs, memo)
  226. )
  227. class NullTranslations(gettext.NullTranslations, object):
  228. DEFAULT_DOMAIN = None
  229. def __init__(self, fp=None):
  230. """Initialize a simple translations class which is not backed by a
  231. real catalog. Behaves similar to gettext.NullTranslations but also
  232. offers Babel's on *gettext methods (e.g. 'dgettext()').
  233. :param fp: a file-like object (ignored in this class)
  234. """
  235. # These attributes are set by gettext.NullTranslations when a catalog
  236. # is parsed (fp != None). Ensure that they are always present because
  237. # some *gettext methods (including '.gettext()') rely on the attributes.
  238. self._catalog = {}
  239. self.plural = lambda n: int(n != 1)
  240. super(NullTranslations, self).__init__(fp=fp)
  241. self.files = list(filter(None, [getattr(fp, 'name', None)]))
  242. self.domain = self.DEFAULT_DOMAIN
  243. self._domains = {}
  244. def dgettext(self, domain, message):
  245. """Like ``gettext()``, but look the message up in the specified
  246. domain.
  247. """
  248. return self._domains.get(domain, self).gettext(message)
  249. def ldgettext(self, domain, message):
  250. """Like ``lgettext()``, but look the message up in the specified
  251. domain.
  252. """
  253. return self._domains.get(domain, self).lgettext(message)
  254. def udgettext(self, domain, message):
  255. """Like ``ugettext()``, but look the message up in the specified
  256. domain.
  257. """
  258. return self._domains.get(domain, self).ugettext(message)
  259. # backward compatibility with 0.9
  260. dugettext = udgettext
  261. def dngettext(self, domain, singular, plural, num):
  262. """Like ``ngettext()``, but look the message up in the specified
  263. domain.
  264. """
  265. return self._domains.get(domain, self).ngettext(singular, plural, num)
  266. def ldngettext(self, domain, singular, plural, num):
  267. """Like ``lngettext()``, but look the message up in the specified
  268. domain.
  269. """
  270. return self._domains.get(domain, self).lngettext(singular, plural, num)
  271. def udngettext(self, domain, singular, plural, num):
  272. """Like ``ungettext()`` but look the message up in the specified
  273. domain.
  274. """
  275. return self._domains.get(domain, self).ungettext(singular, plural, num)
  276. # backward compatibility with 0.9
  277. dungettext = udngettext
  278. # Most of the downwards code, until it get's included in stdlib, from:
  279. # https://bugs.python.org/file10036/gettext-pgettext.patch
  280. #
  281. # The encoding of a msgctxt and a msgid in a .mo file is
  282. # msgctxt + "\x04" + msgid (gettext version >= 0.15)
  283. CONTEXT_ENCODING = '%s\x04%s'
  284. def pgettext(self, context, message):
  285. """Look up the `context` and `message` id in the catalog and return the
  286. corresponding message string, as an 8-bit string encoded with the
  287. catalog's charset encoding, if known. If there is no entry in the
  288. catalog for the `message` id and `context` , and a fallback has been
  289. set, the look up is forwarded to the fallback's ``pgettext()``
  290. method. Otherwise, the `message` id is returned.
  291. """
  292. ctxt_msg_id = self.CONTEXT_ENCODING % (context, message)
  293. missing = object()
  294. tmsg = self._catalog.get(ctxt_msg_id, missing)
  295. if tmsg is missing:
  296. if self._fallback:
  297. return self._fallback.pgettext(context, message)
  298. return message
  299. # Encode the Unicode tmsg back to an 8-bit string, if possible
  300. if self._output_charset:
  301. return text_to_native(tmsg, self._output_charset)
  302. elif self._charset:
  303. return text_to_native(tmsg, self._charset)
  304. return tmsg
  305. def lpgettext(self, context, message):
  306. """Equivalent to ``pgettext()``, but the translation is returned in the
  307. preferred system encoding, if no other encoding was explicitly set with
  308. ``bind_textdomain_codeset()``.
  309. """
  310. ctxt_msg_id = self.CONTEXT_ENCODING % (context, message)
  311. missing = object()
  312. tmsg = self._catalog.get(ctxt_msg_id, missing)
  313. if tmsg is missing:
  314. if self._fallback:
  315. return self._fallback.lpgettext(context, message)
  316. return message
  317. if self._output_charset:
  318. return tmsg.encode(self._output_charset)
  319. return tmsg.encode(locale.getpreferredencoding())
  320. def npgettext(self, context, singular, plural, num):
  321. """Do a plural-forms lookup of a message id. `singular` is used as the
  322. message id for purposes of lookup in the catalog, while `num` is used to
  323. determine which plural form to use. The returned message string is an
  324. 8-bit string encoded with the catalog's charset encoding, if known.
  325. If the message id for `context` is not found in the catalog, and a
  326. fallback is specified, the request is forwarded to the fallback's
  327. ``npgettext()`` method. Otherwise, when ``num`` is 1 ``singular`` is
  328. returned, and ``plural`` is returned in all other cases.
  329. """
  330. ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
  331. try:
  332. tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
  333. if self._output_charset:
  334. return text_to_native(tmsg, self._output_charset)
  335. elif self._charset:
  336. return text_to_native(tmsg, self._charset)
  337. return tmsg
  338. except KeyError:
  339. if self._fallback:
  340. return self._fallback.npgettext(context, singular, plural, num)
  341. if num == 1:
  342. return singular
  343. else:
  344. return plural
  345. def lnpgettext(self, context, singular, plural, num):
  346. """Equivalent to ``npgettext()``, but the translation is returned in the
  347. preferred system encoding, if no other encoding was explicitly set with
  348. ``bind_textdomain_codeset()``.
  349. """
  350. ctxt_msg_id = self.CONTEXT_ENCODING % (context, singular)
  351. try:
  352. tmsg = self._catalog[(ctxt_msg_id, self.plural(num))]
  353. if self._output_charset:
  354. return tmsg.encode(self._output_charset)
  355. return tmsg.encode(locale.getpreferredencoding())
  356. except KeyError:
  357. if self._fallback:
  358. return self._fallback.lnpgettext(context, singular, plural, num)
  359. if num == 1:
  360. return singular
  361. else:
  362. return plural
  363. def upgettext(self, context, message):
  364. """Look up the `context` and `message` id in the catalog and return the
  365. corresponding message string, as a Unicode string. If there is no entry
  366. in the catalog for the `message` id and `context`, and a fallback has
  367. been set, the look up is forwarded to the fallback's ``upgettext()``
  368. method. Otherwise, the `message` id is returned.
  369. """
  370. ctxt_message_id = self.CONTEXT_ENCODING % (context, message)
  371. missing = object()
  372. tmsg = self._catalog.get(ctxt_message_id, missing)
  373. if tmsg is missing:
  374. if self._fallback:
  375. return self._fallback.upgettext(context, message)
  376. return text_type(message)
  377. return tmsg
  378. def unpgettext(self, context, singular, plural, num):
  379. """Do a plural-forms lookup of a message id. `singular` is used as the
  380. message id for purposes of lookup in the catalog, while `num` is used to
  381. determine which plural form to use. The returned message string is a
  382. Unicode string.
  383. If the message id for `context` is not found in the catalog, and a
  384. fallback is specified, the request is forwarded to the fallback's
  385. ``unpgettext()`` method. Otherwise, when `num` is 1 `singular` is
  386. returned, and `plural` is returned in all other cases.
  387. """
  388. ctxt_message_id = self.CONTEXT_ENCODING % (context, singular)
  389. try:
  390. tmsg = self._catalog[(ctxt_message_id, self.plural(num))]
  391. except KeyError:
  392. if self._fallback:
  393. return self._fallback.unpgettext(context, singular, plural, num)
  394. if num == 1:
  395. tmsg = text_type(singular)
  396. else:
  397. tmsg = text_type(plural)
  398. return tmsg
  399. def dpgettext(self, domain, context, message):
  400. """Like `pgettext()`, but look the message up in the specified
  401. `domain`.
  402. """
  403. return self._domains.get(domain, self).pgettext(context, message)
  404. def udpgettext(self, domain, context, message):
  405. """Like `upgettext()`, but look the message up in the specified
  406. `domain`.
  407. """
  408. return self._domains.get(domain, self).upgettext(context, message)
  409. # backward compatibility with 0.9
  410. dupgettext = udpgettext
  411. def ldpgettext(self, domain, context, message):
  412. """Equivalent to ``dpgettext()``, but the translation is returned in the
  413. preferred system encoding, if no other encoding was explicitly set with
  414. ``bind_textdomain_codeset()``.
  415. """
  416. return self._domains.get(domain, self).lpgettext(context, message)
  417. def dnpgettext(self, domain, context, singular, plural, num):
  418. """Like ``npgettext``, but look the message up in the specified
  419. `domain`.
  420. """
  421. return self._domains.get(domain, self).npgettext(context, singular,
  422. plural, num)
  423. def udnpgettext(self, domain, context, singular, plural, num):
  424. """Like ``unpgettext``, but look the message up in the specified
  425. `domain`.
  426. """
  427. return self._domains.get(domain, self).unpgettext(context, singular,
  428. plural, num)
  429. # backward compatibility with 0.9
  430. dunpgettext = udnpgettext
  431. def ldnpgettext(self, domain, context, singular, plural, num):
  432. """Equivalent to ``dnpgettext()``, but the translation is returned in
  433. the preferred system encoding, if no other encoding was explicitly set
  434. with ``bind_textdomain_codeset()``.
  435. """
  436. return self._domains.get(domain, self).lnpgettext(context, singular,
  437. plural, num)
  438. if not PY2:
  439. ugettext = gettext.NullTranslations.gettext
  440. ungettext = gettext.NullTranslations.ngettext
  441. class Translations(NullTranslations, gettext.GNUTranslations):
  442. """An extended translation catalog class."""
  443. DEFAULT_DOMAIN = 'messages'
  444. def __init__(self, fp=None, domain=None):
  445. """Initialize the translations catalog.
  446. :param fp: the file-like object the translation should be read from
  447. :param domain: the message domain (default: 'messages')
  448. """
  449. super(Translations, self).__init__(fp=fp)
  450. self.domain = domain or self.DEFAULT_DOMAIN
  451. if not PY2:
  452. ugettext = gettext.GNUTranslations.gettext
  453. ungettext = gettext.GNUTranslations.ngettext
  454. @classmethod
  455. def load(cls, dirname=None, locales=None, domain=None):
  456. """Load translations from the given directory.
  457. :param dirname: the directory containing the ``MO`` files
  458. :param locales: the list of locales in order of preference (items in
  459. this list can be either `Locale` objects or locale
  460. strings)
  461. :param domain: the message domain (default: 'messages')
  462. """
  463. if locales is not None:
  464. if not isinstance(locales, (list, tuple)):
  465. locales = [locales]
  466. locales = [str(locale) for locale in locales]
  467. if not domain:
  468. domain = cls.DEFAULT_DOMAIN
  469. filename = gettext.find(domain, dirname, locales)
  470. if not filename:
  471. return NullTranslations()
  472. with open(filename, 'rb') as fp:
  473. return cls(fp=fp, domain=domain)
  474. def __repr__(self):
  475. return '<%s: "%s">' % (type(self).__name__,
  476. self._info.get('project-id-version'))
  477. def add(self, translations, merge=True):
  478. """Add the given translations to the catalog.
  479. If the domain of the translations is different than that of the
  480. current catalog, they are added as a catalog that is only accessible
  481. by the various ``d*gettext`` functions.
  482. :param translations: the `Translations` instance with the messages to
  483. add
  484. :param merge: whether translations for message domains that have
  485. already been added should be merged with the existing
  486. translations
  487. """
  488. domain = getattr(translations, 'domain', self.DEFAULT_DOMAIN)
  489. if merge and domain == self.domain:
  490. return self.merge(translations)
  491. existing = self._domains.get(domain)
  492. if merge and existing is not None:
  493. existing.merge(translations)
  494. else:
  495. translations.add_fallback(self)
  496. self._domains[domain] = translations
  497. return self
  498. def merge(self, translations):
  499. """Merge the given translations into the catalog.
  500. Message translations in the specified catalog override any messages
  501. with the same identifier in the existing catalog.
  502. :param translations: the `Translations` instance with the messages to
  503. merge
  504. """
  505. if isinstance(translations, gettext.GNUTranslations):
  506. self._catalog.update(translations._catalog)
  507. if isinstance(translations, Translations):
  508. self.files.extend(translations.files)
  509. return self