Determine the user language in Pyramid

风格不统一 提交于 2019-12-03 05:38:55

Pyramid doesn't dictate how a locale should be negotiated. Basing your site language on the "Accept-Language" header can cause problems as most users do not know how to set their preferred browser languages. Make sure your users can switch languages easily and use a cookie to store that preference for future visits.

You either need to set a _LOCALE_ key on the request (via an event handler, for example), or provide your own custom locale negotiator.

Here's an example using the NewRequest event and the accept_language header, which is an instance of the webob Accept class:

from pyramid.events import NewRequest
from pyramid.events import subscriber

@subscriber(NewRequest)
def setAcceptedLanguagesLocale(event):
    if not event.request.accept_language:
        return
    accepted = event.request.accept_language
    event.request._LOCALE_ = accepted.best_match(('en', 'fr', 'de'), 'en')

Do note that the request._LOCALE_ works only because by default the locale negotiator is a default_locale_negotiator. If you have very complex checks, for example you have to fetch the user from DB if a cookie does not exist, the NewRequest handler does have overhead for requests that do not need any translations. For them you can also use a custom locale negotiator, like:

def my_locale_negotiator(request):
    if not hasattr(request, '_LOCALE_'):
        request._LOCALE_ = request.accept_language.best_match(
            ('en', 'fr', 'de'), 'en')

    return request._LOCALE_


from pyramid.config import Configurator
config = Configurator()
config.set_locale_negotiator(my_locale_negotiator)

As of pyramid 1.5, you can use these request properties to access current locale:

request.localizer an instance of Localizer

request.locale same as request.localizer.locale_name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!