i18n

This module provides internationalization and localization support for webapp2.

To use it, you must add the babel and pytz packages to your application directory (for App Engine) or install it in your virtual environment (for other servers).

You can download babel and pytz from the following locations:

webapp2_extras.i18n.default_config = {'date_formats': {'datetime.iso': "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ", 'time.iso': "HH':'mm':'ss", 'date.full': None, 'datetime.short': None, 'date.long': None, 'time.medium': None, 'date.medium': None, 'time.full': None, 'datetime': 'medium', 'datetime.medium': None, 'time.long': None, 'date.short': None, 'date.iso': "yyyy'-'MM'-'dd", 'time': 'medium', 'date': 'medium', 'datetime.long': None, 'time.short': None, 'datetime.full': None}, 'default_locale': 'en_US', 'translations_path': 'locale', 'default_timezone': 'UTC', 'domains': ['messages'], 'timezone_selector': None, 'locale_selector': None}

Default configuration values for this module. Keys are:

translations_path
Path to the translations directory. Default is locale.
domains
List of gettext domains to be used. Default is ['messages'].
default_locale
A locale code to be used as fallback. Default is 'en_US'.
default_timezone
The application default timezone according to the Olson database. Default is 'UTC'.
locale_selector
A function that receives (store, request) and returns a locale to be used for a request. If not defined, uses default_locale. Can also be a string in dotted notation to be imported.
timezone_selector
A function that receives (store, request) and returns a timezone to be used for a request. If not defined, uses default_timezone. Can also be a string in dotted notation to be imported.
date_formats
Default date formats for datetime, date and time.
class webapp2_extras.i18n.I18nStore(app, config=None)[source]

Internalization store.

Caches loaded translations and configuration to be used between requests.

__init__(app, config=None)[source]

Initializes the i18n store.

Parameters:
date_formats = None

Dictionary of default date formats.

default_locale = None

Default locale code.

default_timezone = None

Default timezone code.

domains = None

Translation domains to merge.

get_translations(locale)[source]

Returns a translation catalog for a locale.

Parameters:locale – A locale code.
Returns:A babel.support.Translations instance, or gettext.NullTranslations if none was found.
load_translations(dirname, locales, domains)[source]

Loads a translation catalog.

Parameters:
  • dirname – Path to where translations are stored.
  • locales – A list of locale codes.
  • domains – A list of domains to be merged.
Returns:

A babel.support.Translations instance, or gettext.NullTranslations if none was found.

locale_selector = None

A callable that returns the locale for a request.

set_locale_selector(func)[source]

Sets the function that defines the locale for a request.

Parameters:func – A callable that receives (store, request) and returns the locale for a request.
set_timezone_selector(func)[source]

Sets the function that defines the timezone for a request.

Parameters:func – A callable that receives (store, request) and returns the timezone for a request.
timezone_selector = None

A callable that returns the timezone for a request.

translations = None

A dictionary with all loaded translations.

translations_path = None

Path to where traslations are stored.

class webapp2_extras.i18n.I18n(request)[source]

Internalization provider for a single request.

__init__(request)[source]

Initializes the i18n provider for a request.

Parameters:request – A webapp2.Request instance.
format_currency(number, currency, format=None)[source]

Returns a formatted currency value. Example:

>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'US$\xa01.099,98'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\xa0\u20ac'

The pattern can also be specified explicitly:

>>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00',
...                 locale='en_US')
u'EUR 1,099.98'
Parameters:
  • number – The number to format.
  • currency – The currency code.
  • format – Notation format.
Returns:

The formatted currency value.

format_date(date=None, format=None, rebase=True)[source]

Returns a date formatted according to the given pattern and following the current locale.

Parameters:
  • date – A date or datetime object. If None, the current date in UTC is used.
  • format

    The format to be returned. Valid values are “short”, “medium”, “long”, “full” or a custom date/time pattern. Example outputs:

    • short: 11/10/09
    • medium: Nov 10, 2009
    • long: November 10, 2009
    • full: Tuesday, November 10, 2009
  • rebase – If True, converts the date to the current timezone.
Returns:

A formatted date in unicode.

format_datetime(datetime=None, format=None, rebase=True)[source]

Returns a date and time formatted according to the given pattern and following the current locale and timezone.

Parameters:
  • datetime – A datetime object. If None, the current date and time in UTC is used.
  • format

    The format to be returned. Valid values are “short”, “medium”, “long”, “full” or a custom date/time pattern. Example outputs:

    • short: 11/10/09 4:36 PM
    • medium: Nov 10, 2009 4:36:05 PM
    • long: November 10, 2009 4:36:05 PM +0000
    • full: Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time
  • rebase – If True, converts the datetime to the current timezone.
Returns:

A formatted date and time in unicode.

format_decimal(number, format=None)[source]

Returns the given decimal number formatted for the current locale. Example:

>>> format_decimal(1.2345, locale='en_US')
u'1.234'
>>> format_decimal(1.2346, locale='en_US')
u'1.235'
>>> format_decimal(-1.2346, locale='en_US')
u'-1.235'
>>> format_decimal(1.2345, locale='sv_SE')
u'1,234'
>>> format_decimal(12345, locale='de')
u'12.345'

The appropriate thousands grouping and the decimal separator are used for each locale:

>>> format_decimal(12345.5, locale='en_US')
u'12,345.5'
Parameters:
  • number – The number to format.
  • format – Notation format.
Returns:

The formatted decimal number.

format_number(number)[source]

Returns the given number formatted for the current locale. Example:

>>> format_number(1099, locale='en_US')
u'1,099'
Parameters:number – The number to format.
Returns:The formatted number.
format_percent(number, format=None)[source]

Returns formatted percent value for the current locale. Example:

>>> format_percent(0.34, locale='en_US')
u'34%'
>>> format_percent(25.1234, locale='en_US')
u'2,512%'
>>> format_percent(25.1234, locale='sv_SE')
u'2\xa0512\xa0%'

The format pattern can also be specified explicitly:

>>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
u'25,123\u2030'
Parameters:
  • number – The percent number to format
  • format – Notation format.
Returns:

The formatted percent number.

format_scientific(number, format=None)[source]

Returns value formatted in scientific notation for the current locale. Example:

>>> format_scientific(10000, locale='en_US')
u'1E4'

The format pattern can also be specified explicitly:

>>> format_scientific(1234567, u'##0E00', locale='en_US')
u'1.23E06'
Parameters:
  • number – The number to format.
  • format – Notation format.
Returns:

Value formatted in scientific notation.

format_time(time=None, format=None, rebase=True)[source]

Returns a time formatted according to the given pattern and following the current locale and timezone.

Parameters:
  • time – A time or datetime object. If None, the current time in UTC is used.
  • format

    The format to be returned. Valid values are “short”, “medium”, “long”, “full” or a custom date/time pattern. Example outputs:

    • short: 4:36 PM
    • medium: 4:36:05 PM
    • long: 4:36:05 PM +0000
    • full: 4:36:05 PM World (GMT) Time
  • rebase – If True, converts the time to the current timezone.
Returns:

A formatted time in unicode.

format_timedelta(datetime_or_timedelta, granularity='second', threshold=0.85)[source]

Formats the elapsed time from the given date to now or the given timedelta. This currently requires an unreleased development version of Babel.

Parameters:
  • datetime_or_timedelta – A timedelta object representing the time difference to format, or a datetime object in UTC.
  • granularity – Determines the smallest unit that should be displayed, the value can be one of “year”, “month”, “week”, “day”, “hour”, “minute” or “second”.
  • threshold – Factor that determines at which point the presentation switches to the next higher unit.
Returns:

A string with the elapsed time.

get_timezone_location(dt_or_tzinfo)[source]

Returns a representation of the given timezone using “location format”.

The result depends on both the local display name of the country and the city assocaited with the time zone:

>>> from pytz import timezone
>>> tz = timezone('America/St_Johns')
>>> get_timezone_location(tz, locale='de_DE')
u"Kanada (St. John's)"
>>> tz = timezone('America/Mexico_City')
>>> get_timezone_location(tz, locale='de_DE')
u'Mexiko (Mexiko-Stadt)'

If the timezone is associated with a country that uses only a single timezone, just the localized country name is returned:

>>> tz = timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Deutschland'
Parameters:dt_or_tzinfo – The datetime or tzinfo object that determines the timezone; if None, the current date and time in UTC is assumed.
Returns:The localized timezone name using location format.
gettext(string, **variables)[source]

Translates a given string according to the current locale.

Parameters:
  • string – The string to be translated.
  • variables – Variables to format the returned string.
Returns:

The translated string.

locale = None

The current locale code.

ngettext(singular, plural, n, **variables)[source]

Translates a possible pluralized string according to the current locale.

Parameters:
  • singular – The singular for of the string to be translated.
  • plural – The plural for of the string to be translated.
  • n – An integer indicating if this is a singular or plural. If greater than 1, it is a plural.
  • variables – Variables to format the returned string.
Returns:

The translated string.

parse_date(string)[source]

Parses a date from a string.

This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string. Example:

>>> parse_date('4/1/04', locale='en_US')
datetime.date(2004, 4, 1)
>>> parse_date('01.04.2004', locale='de_DE')
datetime.date(2004, 4, 1)
Parameters:string – The string containing the date.
Returns:The parsed date object.
parse_datetime(string)[source]

Parses a date and time from a string.

This function uses the date and time formats for the locale as a hint to determine the order in which the time fields appear in the string.

Parameters:string – The string containing the date and time.
Returns:The parsed datetime object.
parse_decimal(string)[source]

Parses localized decimal string into a float. Example:

>>> parse_decimal('1,099.98', locale='en_US')
1099.98
>>> parse_decimal('1.099,98', locale='de')
1099.98

When the given string cannot be parsed, an exception is raised:

>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
   ...
NumberFormatError: '2,109,998' is not a valid decimal number
Parameters:string – The string to parse.
Returns:The parsed decimal number.
Raises:NumberFormatError if the string can not be converted to a decimal number.
parse_number(string)[source]

Parses localized number string into a long integer. Example:

>>> parse_number('1,099', locale='en_US')
1099L
>>> parse_number('1.099', locale='de_DE')
1099L

When the given string cannot be parsed, an exception is raised:

>>> parse_number('1.099,98', locale='de')
Traceback (most recent call last):
   ...
NumberFormatError: '1.099,98' is not a valid number
Parameters:string – The string to parse.
Returns:The parsed number.
Raises:NumberFormatError if the string can not be converted to a number.
parse_time(string)[source]

Parses a time from a string.

This function uses the time format for the locale as a hint to determine the order in which the time fields appear in the string. Example:

>>> parse_time('15:30:00', locale='en_US')
datetime.time(15, 30)
Parameters:string – The string containing the time.
Returns:The parsed time object.
set_locale(locale)[source]

Sets the locale code for this request.

Parameters:locale – A locale code.
set_timezone(timezone)[source]

Sets the timezone code for this request.

Parameters:timezone – A timezone code.
store = None

A reference to I18nStore.

timezone = None

The current timezone code.

to_local_timezone(datetime)[source]

Returns a datetime object converted to the local timezone.

Parameters:datetime – A datetime object.
Returns:A datetime object normalized to a timezone.
to_utc(datetime)[source]

Returns a datetime object converted to UTC and without tzinfo.

Parameters:datetime – A datetime object.
Returns:A naive datetime object (no timezone), converted to UTC.
translations = None

The current translations.

tzinfo = None

The current tzinfo object.

webapp2_extras.i18n.get_store(factory=<class 'webapp2_extras.i18n.I18nStore'>, key='webapp2_extras.i18n.I18nStore', app=None)[source]

Returns an instance of I18nStore from the app registry.

It’ll try to get it from the current app registry, and if it is not registered it’ll be instantiated and registered. A second call to this function will return the same instance.

Parameters:
  • factory – The callable used to build and register the instance if it is not yet registered. The default is the class I18nStore itself.
  • key – The key used to store the instance in the registry. A default is used if it is not set.
  • app – A webapp2.WSGIApplication instance used to store the instance. The active app is used if it is not set.
webapp2_extras.i18n.set_store(store, key='webapp2_extras.i18n.I18nStore', app=None)[source]

Sets an instance of I18nStore in the app registry.

Parameters:
  • store – An instance of I18nStore.
  • key – The key used to retrieve the instance from the registry. A default is used if it is not set.
  • request – A webapp2.WSGIApplication instance used to retrieve the instance. The active app is used if it is not set.
webapp2_extras.i18n.get_i18n(factory=<class 'webapp2_extras.i18n.I18n'>, key='webapp2_extras.i18n.I18n', request=None)[source]

Returns an instance of I18n from the request registry.

It’ll try to get it from the current request registry, and if it is not registered it’ll be instantiated and registered. A second call to this function will return the same instance.

Parameters:
  • factory – The callable used to build and register the instance if it is not yet registered. The default is the class I18n itself.
  • key – The key used to store the instance in the registry. A default is used if it is not set.
  • request – A webapp2.Request instance used to store the instance. The active request is used if it is not set.
webapp2_extras.i18n.set_i18n(i18n, key='webapp2_extras.i18n.I18n', request=None)[source]

Sets an instance of I18n in the request registry.

Parameters:
  • store – An instance of I18n.
  • key – The key used to retrieve the instance from the registry. A default is used if it is not set.
  • request – A webapp2.Request instance used to retrieve the instance. The active request is used if it is not set.
webapp2_extras.i18n.lazy_gettext(string, **variables)[source]

A lazy version of gettext().

Parameters:
  • string – The string to be translated.
  • variables – Variables to format the returned string.
Returns:

A babel.support.LazyProxy object that when accessed translates the string.

webapp2_extras.i18n.gettext(string, **variables)[source]

See I18n.gettext().

webapp2_extras.i18n.ngettext(singular, plural, n, **variables)[source]

See I18n.ngettext().

webapp2_extras.i18n.to_local_timezone(datetime)[source]

See I18n.to_local_timezone().

webapp2_extras.i18n.to_utc(datetime)[source]

See I18n.to_utc().

webapp2_extras.i18n.format_date(date=None, format=None, rebase=True)[source]

See I18n.format_date().

webapp2_extras.i18n.format_datetime(datetime=None, format=None, rebase=True)[source]

See I18n.format_datetime().

webapp2_extras.i18n.format_time(time=None, format=None, rebase=True)[source]

See I18n.format_time().

webapp2_extras.i18n.format_timedelta(datetime_or_timedelta, granularity='second', threshold=0.85)[source]

See I18n.format_timedelta().

webapp2_extras.i18n.format_number(number)[source]

See I18n.format_number().

webapp2_extras.i18n.format_decimal(number, format=None)[source]

See I18n.format_decimal().

webapp2_extras.i18n.format_currency(number, currency, format=None)[source]

See I18n.format_currency().

webapp2_extras.i18n.format_percent(number, format=None)[source]

See I18n.format_percent().

webapp2_extras.i18n.format_scientific(number, format=None)[source]

See I18n.format_scientific().

webapp2_extras.i18n.parse_date(string)[source]

See I18n.parse_date()

webapp2_extras.i18n.parse_datetime(string)[source]

See I18n.parse_datetime().

webapp2_extras.i18n.parse_time(string)[source]

See I18n.parse_time().

webapp2_extras.i18n.parse_number(string)[source]

See I18n.parse_number().

webapp2_extras.i18n.parse_decimal(string)[source]

See I18n.parse_decimal().

webapp2_extras.i18n.get_timezone_location(dt_or_tzinfo)[source]

See I18n.get_timezone_location().

Previous topic

Auth

Next topic

Jinja2

This Page