Den*_*nis 13 python localization pyramid
我想为我的项目做国际化.我按照官方文档中描述的方式进行了描述,但本地化仍无效.以下是我尝试获取用户区域设置的方法:
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
Run Code Online (Sandbox Code Playgroud)
但是request
没有attr"local_name",但它有"Accept-Language",因此当函数get_local_name
在请求中找不到"local_name"时,它会调用另一个函数:
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
Run Code Online (Sandbox Code Playgroud)
我怎么能看到negotiator
尝试从全局环境中获取本地,但是如果它无法从config中设置它的设置值.我无法理解为什么Pyramid没有直接从请求的字段"Accept-Language"获取语言环境?
而且,我如何正确确定区域设置?
Mar*_*ers 14
金字塔没有规定如何协商语言环境.在"Accept-Language"标题上添加站点语言可能会导致问题,因为大多数用户不知道如何设置首选的浏览器语言.确保您的用户可以轻松切换语言,并使用Cookie存储该偏好以供将来访问.
您需要_LOCALE_
在请求上设置密钥(例如,通过事件处理程序),或者提供您自己的自定义区域设置协商器.
这是使用NewRequest
事件和accept_language
标头的示例,它是webob Accept
类的一个实例:
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')
Run Code Online (Sandbox Code Playgroud)