确定金字塔中的用户语言 [英] Determine the user language in Pyramid

查看:134
本文介绍了确定金字塔中的用户语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的项目国际化.我遵循了官方文档中的描述,但是本地化仍然不起作用.这是我尝试获取用户语言环境的方法:

I want to make internationalization for my project. I followed how it is described in official documentation, but localization still doesn't work. Here is how I try get user locale:

def get_locale_name(request):
    """ Return the :term:`locale name` associated with the current
    request (possibly cached)."""
    locale_name = getattr(request, 'locale_name', None)
    if locale_name is None:
       locale_name = negotiate_locale_name(request)
       request.locale_name = locale_name
   return locale_name

但是request没有attr"local_name",但是它具有"Accept-Language",因此当函数get_local_name在请求中未找到"local_name"时,它将调用另一个函数:

But request doesn't have attr "local_name", but it has "Accept-Language" and so when function get_local_name doesn't find "local_name" in the request, it calls another function:

def negotiate_locale_name(request):
    """ Negotiate and return the :term:`locale name` associated with
    the current request (never cached)."""
    try:
        registry = request.registry
    except AttributeError:
        registry = get_current_registry()
    negotiator = registry.queryUtility(ILocaleNegotiator,
                                       default=default_locale_negotiator)
    locale_name = negotiator(request)

   if locale_name is None:
        settings = registry.settings or {}
        locale_name = settings.get('default_locale_name', 'en')

   return locale_name

我如何看到negotiator尝试从全局环境获取本地,但是如果无法从config中获取其设置值. 而且我不明白为什么Pyramid不能直接从请求的字段"Accept-Language"中获取语言环境?

How can I see negotiator try to get local from global environment but if it cant to do that its set value from config. And I cant understand why Pyramid doesn't get locale directly from request's field "Accept-Language"?

而且,如何正确确定语言环境?

And, how can I make a correct determination of the locale?

推荐答案

金字塔不规定如何协商语言环境.由于大多数用户不知道如何设置其首选的浏览器语言,因此将网站语言置于"Accept-Language"标头上会引起问题.确保您的用户可以轻松切换语言,并使用Cookie存储该偏好设置,以供将来访问.

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.

您要么需要设置以下是使用 NewRequest事件 webob Accept:

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')

这篇关于确定金字塔中的用户语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆