this_framework.py 1.15 KB
from pyramid.threadlocal import get_current_registry
from pyramid.events import (
    subscriber,
    BeforeRender,
    )
from pyramid.i18n import default_locale_negotiator


LOCALE_NAMES = {
    'en': 'English',
    'id': 'Indonesia',
    }
LOCALE_IDS = list(LOCALE_NAMES.keys())


def get_settings():
    return get_current_registry().settings


def get_locale_should_be(request):
    if 'HTTP_ACCEPT_LANGUAGE' not in request.environ:
        return 'id'
    # id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7
    vals = request.environ['HTTP_ACCEPT_LANGUAGE'].split(',')
    for val in vals:
        for locale_id in LOCALE_IDS:
            if val.find(locale_id) == 0:
                return locale_id


def get_locale_name(request):
    return default_locale_negotiator(request) or \
            get_locale_should_be(request)


def get_locale_title(name):
    if name in LOCALE_NAMES:
        return LOCALE_NAMES[name]
    return name


def get_locale_title_(request):
    name = get_locale_name(request)
    return get_locale_title(name)


@subscriber(BeforeRender)
def add_global(event):
    event['locale_name'] = get_locale_title_
    event['locale_should_be'] = get_locale_should_be