Skip to content

Instantly share code, notes, and snippets.

@wichert
Created September 27, 2011 12:02
Show Gist options
  • Save wichert/1244896 to your computer and use it in GitHub Desktop.
Save wichert/1244896 to your computer and use it in GitHub Desktop.
Accept-Language aware locale negotiator for Pyramid
#: 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