Source code for shoop.utils.i18n
# -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import babel
import babel.numbers
from babel.dates import format_datetime
from babel.numbers import format_currency
from django.apps import apps
from django.utils import translation
from django.utils.lru_cache import lru_cache
from django.utils.timezone import localtime
from django.views.decorators.cache import cache_page
from django.views.i18n import javascript_catalog
@lru_cache()
[docs]def get_babel_locale(locale_string):
"""
Parse a Django-format (dash-separated) locale string
and return a Babel locale.
This function is decorated with lru_cache, so executions
should be cheap even if `babel.Locale.parse()` most definitely
is not.
:param locale_string: A locale string ("en-US", "fi-FI", "fi")
:type locale_string: str
:return: Babel Locale
:rtype: babel.Locale
"""
return babel.Locale.parse(locale_string, "-")
[docs]def get_current_babel_locale(fallback="en-US-POSIX"):
"""
Get a Babel locale based on the thread's locale context.
:param fallback:
Locale to fallback to; set to None to raise an exception instead.
:return: Babel Locale
:rtype: babel.Locale
"""
locale = get_babel_locale(locale_string=translation.get_language())
if not locale:
if fallback:
locale = get_babel_locale(fallback)
if not locale:
raise ValueError(
"Failed to get current babel locale (lang=%s)" %
(translation.get_language(),))
return locale
[docs]def get_language_name(language_code):
"""
Get a language's name in the currently active locale.
:param language_code: Language code (possibly with an added script suffix (zh_Hans, zh-Hans))
:type language_code: str
:return: The language name, or the code if the language couldn't be derived.
:rtype: str
"""
try:
lang_dict = get_current_babel_locale().languages
except (AttributeError, ValueError): # The locale lookup failed,
return language_code # so return the code as-is.
for option in (
language_code,
str(language_code).replace("-", "_"),
):
if option in lang_dict:
return lang_dict[option]
return language_code
@cache_page(3600)
[docs]def javascript_catalog_all(request, domain='djangojs'):
"""
Get JavaScript message catalog for all apps in INSTALLED_APPS.
"""
all_apps = [x.name for x in apps.get_app_configs()]
return javascript_catalog(request, domain, all_apps)
[docs]def get_currency_name(currency):
locale = get_current_babel_locale()
return babel.numbers.get_currency_name(currency, locale=locale)