this_framework.py 1.98 KB
from pyramid.events import (
    subscriber,
    BeforeRender,
)
from pyramid.i18n import default_locale_negotiator
from pyramid.interfaces import IAuthenticationPolicy, IAuthorizationPolicy
from pyramid.security import Allowed
from pyramid.threadlocal import get_current_registry

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)


# def api_has_permission_(request, permission, context=None):
#     if context is None:
#         context = request.context
#     reg = request.registry
#     authn_policy = reg.queryUtility(IAuthenticationPolicy)
#     if authn_policy is None:
#         return Allowed('No authentication policy in use.')
#     authz_policy = reg.queryUtility(IAuthorizationPolicy)
#     if authz_policy is None:
#         raise ValueError(
#             'Authentication policy registered without '
#             'authorization policy'
#         )  # should never happen
#     principals = authn_policy.effective_principals(request)
#     return authz_policy.permits(context, principals, permission)


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