def setUp(self): self.default_locale = babel.default_locale() self.foreign_locale = babel.Locale("it") if self.foreign_locale == self.default_locale: self.foreign_locale = babel.Locale("de") self.local_timezone = tzlocal.get_localzone() self.foreign_timezone = pytz.timezone("US/Eastern") if self.foreign_timezone == self.local_timezone: self.foreign_timezone = pytz.timezone("Europe/Berlin")
def time_ago(x): """ Convert a datetime to a string. """ # If the date is more than one week ago, then display the actual date instead of in words if datetime.utcnow() - x > timedelta(weeks=1): # Greater than a week difference return x.strftime("%b %d, %Y") else: # Workaround https://github.com/python-babel/babel/issues/137 kwargs = dict() if not default_locale('LC_TIME'): kwargs['locale'] = 'en_US_POSIX' return format_timedelta(x - datetime.utcnow(), threshold=1, add_direction=True, **kwargs)
def init(self, locale_map=None): locale = default_locale() or 'en' translator = Translator(locale, locale_map or {}) pylons.translator._push_object(translator) config_file = find_config(default=None) parser = self.create_parser(config_file) options = parser.parse_args() if not options.config: parser.error(_('Please specify a config file using "--config=<filename>"')) init_mediacore(options.config) self.validate_options(options, parser) self.options = options return self
def init(self, locale_map=None): locale = default_locale() or 'en' translator = Translator(locale, locale_map or {}) pylons.translator._push_object(translator) config_file = find_config(default=None) parser = self.create_parser(config_file) options = parser.parse_args() if not options.config: parser.error( _('Please specify a config file using "--config=<filename>"')) init_mediacore(options.config) self.validate_options(options, parser) self.options = options return self
def setup_languages(settings): if not settings['language']: try: settings['language'] = [default_locale()[:2]] except ValueError: settings['language'] = ['en'] languages = [] language_names = [] for lang_code in settings['language']: try: language_names.append(Locale(lang_code).english_name) languages.append(lang_code) except UnknownLocaleError: raise click.ClickException('Unknown language code: %s' % lang_code) logger.info('Languages: %s', ', '.join(language_names)) return settings
def __init__(self, command_name="!date", timezone=None, locale=None, **kwargs): super().__init__(command_name, **kwargs) if pytz is None: logging.warn("Timezone support disabled, install pytz to enable.") self.argparse.set_defaults(timezone=None) else: if timezone is None: timezone = pytz.UTC else: timezone = pytz.timezone(timezone) self.argparse.add_argument( "timezone", nargs="?", default=timezone, type=self.to_timezone, help="Timezone (default is {}). Examples: " "Europe/Berlin, US/Eastern, ETC/GMT+2".format(timezone) ) if babel.dates is None: logging.warn("Localization support is disabled, " "install babel to enable.") self.argparse.set_defaults(locale=None) else: if locale is None: locale = babel.default_locale() self.argparse.add_argument( "-l", "--lang", "--locale", default=locale, dest="locale", help="Locale for the output (default is {}). Examples: " "en_GB, de_DE".format(locale) ) self.argparse.add_argument( "-f", "--format", choices={"short", "long", "medium", "full"}, default="full", help="Format of the output (default is full)." )
def format(self, locale=None, pattern=None): """ Return a locale-aware, currency-formatted string. This method emulates babel.numbers.format_currency(). A specific locale identifier (language[_territory]) can be passed, otherwise the system's default locale will be used. A custom formatting pattern of the form "¤#,##0.00;(¤#,##0.00)" (positive[;negative]) can also be passed, otherwise it will be determined from the locale and the CLDR (Unicode Common Locale Data Repository) included with Babel. >>> m = Money('1234.567', 'EUR') >>> m.format() # assuming the system's locale is 'en_US' €1,234.57 >>> m.format('de_DE') # German formatting 1.234,57 € >>> m.format('de', '#,##0 ¤') # German formatting (short), no cents 1.235 € >>> m.format(pattern='#,##0.00 ¤¤¤') # Default locale, full name 1,235.57 euro Learn more about this formatting syntaxis at: http://www.unicode.org/reports/tr35/tr35-numbers.html """ if BABEL_AVAILABLE: if not locale: locale = babel.default_locale('LC_NUMERIC') locale = babel.Locale.parse(locale) if not pattern: pattern = locale.currency_formats.get(pattern) pattern = babel.numbers.parse_pattern(pattern) return pattern.apply(self._amount, locale, currency=self._currency) else: raise NotImplementedError("formatting requires Babel " "(https://pypi.python.org/pypi/Babel)")
def format(self, locale=None, pattern=None): """ Return a locale-aware, currency-formatted string. This method emulates babel.numbers.format_currency(). A specific locale identifier (language[_territory]) can be passed, otherwise the system's default locale will be used. A custom formatting pattern of the form "¤#,##0.00;(¤#,##0.00)" (positive[;negative]) can also be passed, otherwise it will be determined from the locale and the CLDR (Unicode Common Locale Data Repository) included with Babel. >>> m = Money('1234.567', 'EUR') >>> m.format() # assuming the system's locale is 'en_US' €1,234.57 >>> m.format('de_DE') # German formatting 1.234,57 € >>> m.format('de', '#,##0 ¤') # German formatting (short), no cents 1.235 € >>> m.format(pattern='#,##0.00 ¤¤¤') # Default locale, full name 1,235.57 euro Learn more about this formatting syntaxis at: http://www.unicode.org/reports/tr35/tr35-numbers.html """ if BABEL_AVAILABLE: if not locale: locale = babel.default_locale('LC_NUMERIC') locale = babel.Locale.parse(locale) if not pattern: pattern = locale.currency_formats.get(pattern) pattern = babel.numbers.parse_pattern(pattern) return pattern.apply(self.amount, locale, currency=self.currency) else: raise NotImplementedError("formatting requires Babel " "(https://pypi.python.org/pypi/Babel)")
def test_init_default(self): formatter = i18n.LocalizingFormatter() self.assertEqual(formatter.locale, babel.default_locale()) self.assertEqual(formatter.tzinfo, self.local_timezone)
from .exceptions import (CurrencyMismatch, ExchangeRateNotFound, InvalidOperandType) __all__ = ['Money', 'XMoney'] BABEL_AVAILABLE = False BABEL_VERSION = None REGEX_CURRENCY_CODE = re.compile("^[A-Z]{3}$") LC_NUMERIC = None try: import babel import babel.numbers BABEL_AVAILABLE = True BABEL_VERSION = StrictVersion(babel.__version__) LC_NUMERIC = babel.default_locale('LC_NUMERIC') except ImportError: pass class Money(object): """Money class with a decimal amount and a currency""" def __init__(self, amount="0", currency=None): try: self._amount = decimal.Decimal(amount) except decimal.InvalidOperation: # RADAR: Python2 money.six.raise_from( ValueError("amount value could not be " "converted to Decimal(): '{}'".format(amount)), None)
InvalidOperandType) __all__ = ['Money', 'XMoney'] BABEL_AVAILABLE = False BABEL_VERSION = None REGEX_CURRENCY_CODE = re.compile("^[A-Z]{3}$") LC_NUMERIC = None try: import babel import babel.numbers BABEL_AVAILABLE = True BABEL_VERSION = StrictVersion(babel.__version__) LC_NUMERIC = babel.default_locale('LC_NUMERIC') except ImportError: pass class Money(object): """Money class with a decimal amount and a currency""" def __init__(self, amount="0", currency=None): try: self._amount = decimal.Decimal(amount) except decimal.InvalidOperation: raise ValueError("amount value could not be converted to " "Decimal(): '{}'".format(amount)) if currency in [None, False, '']: raise ValueError("invalid currency value: '{}'".format(currency))
def _get_l10n(self, prop, locale): """Collapses an internationalized field into a localized one.""" messages = self.get("metadata", {}).get(prop, {}) return messages.get(locale) or messages.get( Locale.parse(default_locale()).language )
def test_auto_format_locale_numeric(self): locale = babel.default_locale('LC_NUMERIC') babel_formatted = babel.numbers.format_currency(self.money.amount, self.money.currency, locale=locale) self.assertEqual(self.money.format(), babel_formatted)
def __init__(self, locale=None, tzinfo=None): super().__init__() self.locale = locale if locale is not None else babel.default_locale() self.tzinfo = tzinfo if tzinfo is not None else tzlocal.get_localzone()
import pandas as pd import jinja2 import weasyprint import os.path import sys, os import locale #import xlrd # just as a reminder that we need to install this package import babel # On a tested windows machine, babel wouldn't work because there # was no current locale set. Apparently, there is no `LC_NUMERIC` # environment variable, so the babel default locale of # `babel.default_locale('LC_NUMERIC')` returns `None` # Solution: Set the environment variable 'LC_ALL' since it will # also help with the non-existing 'LC_TIME' for example: mylocale = locale.getlocale()[0] if babel.default_locale('LC_NUMERIC') is None: if os.getenv('LC_ALL') is None: os.environ['LC_ALL'] = mylocale # it is important to import these after the fix made above: import babel.numbers, babel.dates # Jinja2 documentation: https://jinja.palletsprojects.com/en/2.11.x/ # https://jinja.palletsprojects.com/en/2.11.x/api/ # https://jinja.palletsprojects.com/en/2.11.x/templates/ # http://babel.pocoo.org/en/latest/numbers.html#numbers # http://babel.pocoo.org/en/latest/dates.html#date-and-time # different ways to center text in html: https://www.computerhope.com/issues/ch001474.htm # https://weasyprint.readthedocs.io/en/stable/tips-tricks.html # Optional whitespace escaping: https://svn.python.org/projects/external/Jinja-1.1/docs/build/escaping.html
def get_locale(): return default_locale()
def _init_translate(self, alert): """Run in background at startup, initializes data, contacts server, does that sort of setup procedure. """ # XXX: Maybe instead of failing here, how about creating a transient # local server, would use whatever web APIs possible. Not really # sure. if not self.client.can_connect(): self.remove_alert(alert) self._create_alert( _("Connection error"), _("Couldn't connect to the server!")) from_lang_store = self.lang_from.get_model() # Try to set the default from language selection to the user's # locale. # XXX: If default_locale fails (theoretically could if ENV isn't # proper), this will raise babel.core.UnknownLocaleError. locale = babel.default_locale(category="LANG") self.locale = Locale(locale) self._logger.info("Setting locale to %s", repr(self.locale)) pairs = self.client.language_pairs() from_langs = set() # TODO: maybe try falling back to first two letters? for pair in pairs: try: from_locale = Locale.parse(pair[0]) from_name = from_locale.get_language_name(self.locale) except (babel.UnknownLocaleError, ValueError): # Fall back to language code from_name = pair[0] self._logger.error('Failed to get a locale for %s', pair[0]) from_langs.add((pair[0], from_name)) from_langs = sorted(list(from_langs), (lambda x, y: cmp(x[1], y[1]))) for lang in from_langs: from_lang_store.append(lang) # Fall back to whatever the first option is. self.lang_from.set_active(0) for idx, lang in enumerate(from_langs): # Check if the user's locale is "good enough". # # e.g. if locale is "en_US", and "en" is in the combobox, then will # return non-None. if babel.negotiate_locale([lang[0]], [locale]) is not None: self.lang_from.set_active(idx) break # Make sure the to_lang combobox is up to date self._lang_from_changed_cb(self.lang_from) # Enable the button self.translate_button.set_sensitive(True) self.remove_alert(alert)
def test_auto_format_locale_numeric(self): locale = babel.default_locale('LC_NUMERIC') babel_formatted = babel.numbers.format_currency(self.price.amount, self.price.currency, locale=locale) self.assertEqual(self.price.format(), babel_formatted)
def get_locale(): return default_locale() or 'en'