diff options
-rw-r--r-- | development.ini | 1 | ||||
-rw-r--r-- | fietsboek/__init__.py | 33 |
2 files changed, 33 insertions, 1 deletions
diff --git a/development.ini b/development.ini index a93c838..15250c4 100644 --- a/development.ini +++ b/development.ini @@ -27,6 +27,7 @@ retry.attempts = 3 email.from = fietsboek@kingdread.de email.smtp_url = debug://localhost:1025 +available_locales = en de enable_account_registration = true session_key = hklurha7ildshgfljhrbuajelghug diff --git a/fietsboek/__init__.py b/fietsboek/__init__.py index 80b6c7d..98e6846 100644 --- a/fietsboek/__init__.py +++ b/fietsboek/__init__.py @@ -4,11 +4,39 @@ For more information, see the README or the included documentation. """ from pyramid.config import Configurator from pyramid.session import SignedCookieSessionFactory -from pyramid.settings import asbool +from pyramid.settings import asbool, aslist +from pyramid.i18n import default_locale_negotiator from .security import SecurityPolicy +def locale_negotiator(request): + """Negotiates the right locale to use. + + This tries the following: + 1. It runs the default negotiator. This allows the locale to be overriden + by using the _LOCALE_ query parameter. + 2. It uses the `Accept-Language`_ header. + + .. Accept-Language: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language + + :param request: The request for which to get the language. + :type request: pyramid.request.Request + :return: The determined locale, or ``None`` if the default should be used. + :rtype: str + """ + locale = default_locale_negotiator(request) + if locale: + return locale + + installed_locales = request.registry.settings['available_locales'] + sentinel = object() + negotiated = request.accept_language.lookup(installed_locales, default=sentinel) + if negotiated is sentinel: + return None + return negotiated + + def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ @@ -18,6 +46,8 @@ def main(global_config, **settings): settings['enable_account_registration'] = asbool( settings.get('enable_account_registration', 'false')) + settings['available_locales'] = aslist( + settings.get('available_locales', 'en')) my_session_factory = SignedCookieSessionFactory(settings['session_key']) with Configurator(settings=settings) as config: @@ -28,4 +58,5 @@ def main(global_config, **settings): config.add_translation_dirs('fietsboek:locale/') config.set_session_factory(my_session_factory) config.set_security_policy(SecurityPolicy()) + config.set_locale_negotiator(locale_negotiator) return config.make_wsgi_app() |