Created
September 27, 2011 12:02
-
-
Save wichert/1244896 to your computer and use it in GitHub Desktop.
Accept-Language aware locale negotiator for Pyramid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#: Mapping of language codes send by browsers to supported dialects. | |
BROWSER_LANGUAGES = { | |
'en-CA': 'en_CA', | |
'en-GB': 'en_GB', | |
'en-US': 'en_GB', | |
'en': 'en_GB', | |
'nl': 'nl_NL', | |
'nl-NL': 'nl_NL', | |
'nl-BE': 'nl_NL', | |
'zh': 'zh_CN', | |
'zh-CN': 'zh_CN', | |
'zh-TW': 'zh_TW', | |
} | |
def locale_negotiator(request): | |
"""Locale negotiator for pyramid views. | |
This version differs from Pyramid's :py:func:`default_locale_negotiator | |
<pyramid.i18n.default_locale_negotiator>` in that it prefers the preferred | |
locale of the currently authenticated user, and has a fallback to the | |
preferred languages from browser. | |
""" | |
userid = authenticated_userid(request) | |
if userid is not None: | |
from s4u.dataentry.model.account import Account # Circular import :( | |
account = meta.Session.query(Account).get(userid) | |
return account.locale | |
locale = default_locale_negotiator(request) | |
if locale is None and request.accept_language: | |
locale = request.accept_language.best_match(BROWSER_LANGUAGES) | |
locale = BROWSER_LANGUAGES.get(locale) | |
return locale |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment