Allspeak Allspeak

API

Allspeak

A class that inherit from both I18n and L10n classes.

class allspeak.Allspeak(*args, **kwargs)
Parameters:
  • folderpath – path that will be searched for the translations.
  • get_locale – a callable that returns the current locale
  • get_timezone – a callable that returns the current timezone
  • default_locale – default locale (as a string or as a Babel.Locale instance). This value will be accepted without checking if it’s available.
  • default_timezone – default timezone (as a string or as a datetime.tzinfo instance).
  • markup – overwrite the function used by translate to flags HTML code as ‘safe’. markupsafe.Markup is used by default.
  • date_formats – update the defaults date formats.

I18n

class allspeak.I18n(folderpath='locales', markup=<class 'markupsafe.Markup'>, **kwargs)

Internationalization functions.

Uses the Reader class to load and parse the translations files.

Parameters:
  • folderpath – path that will be searched for the translations.
  • get_locale – a callable that returns the current locale
  • default_locale – default locale (as a string or as a Babel.Locale instance). This value will be accepted without checking if it’s available.
  • markup – overwrite the function used by translate to flags HTML code as ‘safe’. markupsafe.Markup is used by default.
get_translations_from_locale(locale)

Return the available translations for a locale: the country-specific (is defined) and the one for the language in general.

Parameters:locale – must be a babel.core.Locale instance or a string.
key_lookup(locale, key)

Return the value of the translation for the given key using the current locale. It tries first with the country-specific (eg en-US) translations (if the locale it’s that specific) and then with those of the general language (eg. en).

Parameters:
  • locale – must be a babel.core.Locale instance or a string.
  • key – a string, the ID of the looked up translation
negotiate_locale(preferred, available=None)

From the available locales, negotiate the most adequate for the client, based on the “accept language” header.

Parameters:
  • preferred – list of the user’s preferred locales (as ISO 639-1 language codes or as Babel.Locale instances).
  • available – optional list of available locales (as ISO 639-1 language codes or as Babel.Locale instances). If provided, overwrites the list of detected locales from the files in folderpath.
test_for_incomplete_locales(*locales)

Check a list of locales for keys that are defined in one but not in the other.

Parameters:locales – two or more locales as strings. If not provided, all of the available locales are tested.
Returns:a dictionary with strlocales as keys and sets of missing keys for those locales as values.
translate(key, count=None, locale=None, **kwargs)

Get the translation for the given key using the current locale.

If the value is a dictionary, and count is defined, uses the value whose key is that number. If that key doesn’t exist, a ‘n’ key is tried instead. If that doesn’t exits either, an empty string is returned.

The final value is formatted using kwargs (and also count if available) so the format placeholders must be named instead of positional.

If the value isn’t a dictionary or a string, is returned as is.

Examples:

>>> translate('hello_world')
'hello {what}'
>>> translate('hello_world', what='world')
'hello world'
>>> translate('a_list', what='world')
['a', 'b', 'c']
Parameters:
  • key – a string, the ID of the looked up translation
  • count – If the value is a dictionary, and count is defined, uses the value whose key is that number. If that key doesn’t exist, a ‘n’ key is tried instead. If that doesn’t exits either, an empty string is returned.
  • locale – must be a babel.core.Locale instance or a string.
  • **kwargs

    for string interpolation of the value.

allspeak.pluralize(dic, count, locale='en')

Takes a dictionary and a number and return the value whose key in the dictionary is either

  1. that number, or
  2. the textual representation of that number according to the CLDR rules for that locale, Depending of the language, this can be: “zero”, “one”, “two”, “few”, “many” or “other”.

As a deviation of the standard:

  • If count is 0, a ‘zero’ is tried
  • If the textual representation is ‘other’ but that key doesn’t exists, a ‘many’ key is tried instead.

Finally, if none of these exits, an empty string is returned.

Examples:

>>> dic = {
        0: u'No apples',
        1: u'One apple',
        3: u'Few apples',
        'many': u'{count} apples',
    }
>>> pluralize(dic, 0)
'No apples'
>>> pluralize(dic, 1)
'One apple'
>>> pluralize(dic, 3)
'Few apples'
>>> pluralize(dic, 10)
'{count} apples'
>>> dic = {
        'zero': u'No apples whatsoever',
        'one': u'One apple',
        'other': u'{count} apples',
    }
>>> pluralize(dic, 0)
u'No apples whatsoever'
>>> pluralize(dic, 1)
'One apple'
>>> pluralize(dic, 2)
'{count} apples'
>>> pluralize(dic, 10)
'{count} apples'
>>> pluralize({0: 'off', 'many': 'on'}, 3)
'on'
>>> pluralize({0: 'off', 'other': 'on'}, 0)
'off'
>>> pluralize({0: 'off', 'other': 'on'}, 456)
'on'
>>> pluralize({}, 3)

Note that this function does not interpolate the string, just returns the right one for the value of count.

L10n

class allspeak.L10n(date_formats=None, **kwargs)

Localization functions.

Parameters:
  • get_locale – a callable that returns the current locale
  • get_timezone – a callable that returns the current timezone
  • default_locale – default locale (as a string or as a Babel.Locale instance). This value will be accepted without checking if it’s available.
  • default_timezone – default timezone (as a string or as a datetime.tzinfo instance).
  • date_formats – update the defaults date formats.
format(value, *args, **kwargs)

Return a formatted value according to the detected type and given parameters.

It doesn’t know anything about currency, percent or scientific formats, so use the other methods for those cases.

format_currency(number, currency, format=None, locale=None, **kwargs)

Return the given number formatted for the locale in the current request.

Parameters:
  • number – the number to format
  • currency – the currency code
  • format – the format to use as documented by Babel.
  • locale – Overwrite the global locale.
format_date(date=None, format=None, rebase=True, locale=None, tzinfo=None, **kwargs)

Return a date formatted according to the given pattern.

Parameters:
  • date – A datetime.datetime or datetime.date object. If no object is passed, the current datetime is assumed.
  • format

    The format parameter can either be ‘short’, ‘medium’, ‘long’ or ‘full’ (in which cause the language’s default for that setting is used) or a format string as documented by Babel.

  • rebase – Convert the given date to the users’s timezone (as returned by to_user_timezone()) By default rebasing happens.
  • locale – Overwrite the global locale.
  • tzinfo – Overwrite the global timezone.
format_datetime(datetime=None, format=None, rebase=True, locale=None, tzinfo=None, **kwargs)

Return a datetime formatted according to the given pattern.

Parameters:
  • datetime – A datetime.datetime object. If no object is passed, the current datetime is assumed.
  • format

    The format parameter can either be ‘short’, ‘medium’, ‘long’ or ‘full’ (in which cause the language’s default for that setting is used) or a format string as documented by Babel.

  • rebase – Convert the given date to the users’s timezone (as returned by to_user_timezone()) By default rebasing happens.
  • locale – Overwrite the global locale.
  • tzinfo – Overwrite the global timezone.
format_decimal(number, format=None, locale=None, **kwargs)

Return the given decimal number formatted for the locale in the current request.

Parameters:
  • number – the number to format
  • format

    the format to use as documented by Babel.

  • locale – Overwrite the global locale.
format_number(number, locale=None, **kwargs)

Return the given number formatted for the locale in the current request.

Parameters:
  • number – the number to format
  • locale – Overwrite the global locale.
format_percent(number, format=None, locale=None, **kwargs)

Return a percent value formatted for the locale in the current request.

Parameters:
  • number – the number to format
  • format

    the format to use as documented by Babel.

  • locale – Overwrite the global locale.
format_scientific(number, format=None, locale=None, **kwargs)

Return value formatted in scientific notation for the locale in the current request.

Parameters:
  • number – the number to format
  • format

    the format to use as documented by Babel.

  • locale – Overwrite the global locale.
format_time(time=None, format=None, rebase=True, locale=None, tzinfo=None, **kwargs)

Return a time formatted according to the given pattern.

Parameters:
  • time – A time or datetime object. If no object is passed, the current time is assumed.
  • format

    The format parameter can either be ‘short’, ‘medium’, ‘long’ or ‘full’ (in which cause the language’s default for that setting is used) or a format string as documented by Babel.

  • rebase – Convert the given time to the users’s timezone (as returned by to_user_timezone()). By default rebasing happens.
  • locale – Overwrite the global locale.
  • tzinfo – Overwrite the global timezone.
format_timedelta(datetime_or_timedelta, granularity='second', threshold=0.85, add_direction=False, format='medium', locale=None, **kwargs)

Format the elapsed time from the given date to now or the given timedelta as documented in babel.dates.format_timedelta().

Parameters:
  • delta – a timedelta object representing the time difference to format, or the delta in seconds as an int value.
  • 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.
  • add_direction – if this flag is set to True the return value will include directional information. For instance a positive timedelta will include the information about it being in the future, a negative will be information about the value being in the past.
  • format – the format (currently only “medium” and “short” are supported)
  • locale – Overwrite the global locale.
set_date_formats(date_formats)

Update the default date and time formats used by self.format* for all locales when called without a format argument.

These are the defaults:

{
  'time': 'medium',
  'date': 'medium',
  'datetime': 'medium',
}
to_user_timezone(datetime, tzinfo=None)

Convert a datetime object to the user’s timezone. This automatically happens on all date formatting unless rebasing is disabled. If you need to convert a datetime.datetime object at any time to the user’s timezone (as returned by get_timezone this function can be used).

to_utc(datetime, tzinfo=None)

Convert a datetime object to UTC and drop tzinfo.

Reader

class allspeak.Reader(folderpath='locales')

Functions related to loading and parsing translation files.

Parameters:folderpath – path or a list of paths (relative or absolute) that will be searched for the translations.
get_loader(filepath)

Get the file loader suitable for a specific file.

load_translations(folderpath=None, locales=None)

Search for locale files on folderpath, load and parse them to build a big dictionary with all the translations data.

Only the files with an extension listed in loaders_ext are loaded because only them have a registered loader.

Parameters:
  • folderpath – overwrite the stored locales folder or list of folders.
  • locales – does nothing, but might be useful to implement load-on-demand in your own subclass.
register_loader(ext, func)

Register a loader for a file extension. func must take a single argument with the full path of a locale file and return a dictionary with the data.

RequestManager

class allspeak.RequestManager(get_locale=None, get_timezone=None, default_locale='en', default_timezone=<UTC>, get_request=None, available_locales=None)

A base class with methods for getting the locale and timezone.

Parameters:
  • get_locale – a callable that returns the current locale
  • get_timezone – a callable that returns the current timezone
  • default_locale – default locale (as a string or as a Babel.Locale instance). This value will be accepted without checking if it’s available.
  • default_timezone – default timezone (as a string or as a datetime.tzinfo instance).
  • get_request – a callable that returns the current request. Do not use this, it exist only for backwards compatibility.
set_defaults(default_locale, default_timezone)

Set the default locale from the configuration as an instance of babel.core.Locale and the default timezone as a datetime.tzinfo.

Integrations

allspeak.get_werkzeug_preferred_locales(request)

Return a list of preferred languages from a werkzeug.wrappers.Request instance.

allspeak.get_webob_preferred_locales(request)

Return a list of preferred languages from a webob.Request instance.

allspeak.get_django_preferred_locales(request)

Take a django.HttpRequest instance and return a list of preferred languages from the headers.

Utilities

allspeak.normalize_locale(locale)
allspeak.normalize_timezone(tzinfo)
allspeak.split_locale(locale)

Returns a tuple (language, TERRITORY) or just (language, ) from a a babel.core.Locale instance or a string like en-US or en_US.

allspeak.locale_to_str(locale)