我想利用webapp2的新功能进行本地化,该功能还具有针对时间和货币的特定于语言环境的格式。
Django有一个很好的函数叫做get_language_from_request,我在完全迁移到webapp2之前就已经使用了,我现在使用webapp2中的i18n代替我可以在用gettext编写的本地化之间切换,并编译成名为messages.mo的文件我的应用程序可以阅读和显示。然后我确定并优先考虑以下方法来获取用户的语言:
1. HTTP GET例如。 hl = pt-br为巴西葡萄牙语
2. HTTP SESSION变量我称之为i18n_language
我应该设置和获取Cookie,但我不知道具体如何
4. HTTP标头我可以得到,在这里我也不知道其中任何一个我正在寻找djnango如何用我曾经使用的方便的get_language_from_request
来做它现在我已经退出导入django而我仍然想要我现在基于webapp2的代码的这个功能。
def get_language_from_request(self, request):
"""
Analyzes the request to find what language the user wants the system to
show. If the user requests a sublanguage where we have a main language, we send
out the main language.
"""
if self.request.get('hl'):
self.session['i18n_language'] = self.request.get('hl')
return self.request.get('hl')
if self.session:
lang_code = self.session.get('i18n_language', None)
if lang_code:
logging.info('language found in session')
return lang_code
lang_code = Cookies(self).get(LANGUAGE_COOKIE_NAME)
if lang_code:
logging.info('language found in cookies')
return lang_code
accept = os.environ.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in self.parse_accept_lang_header(accept):
logging.info('accept_lang:'+accept_lang)
lang_code = accept_lang
return lang_code
我看到django代码可用,但我不知道webapp2的i18n有多少,例如我必须处理pt-br等语言的后备,如果没有,应该回到pt。 pt-br的mo定位和其他方言的类似。
实际上设置我可以使用的语言
i18n.get_i18n().set_locale(language)
我请求您的帮助,优先考虑获取用户语言的不同方法,我也想了解您如何继续实施的想法。或者你认为我只能使用会话变量,而不是这个彻底的“完整”解决方案,因为我无论如何主要修复语言的地理用法我现在唯一实际使用的翻译是巴西葡萄牙语和英语但我想要它还准备好切换到西班牙语,俄语和其他语言,因此我希望能够切换到用户语言,至少将其保存到webapp2会话,并知道你对使用cookie和标题来获取用户的想法语言。
我曾经从django获得si的原始代码看起来像这样,我不能再使用它,因为它被锁定到django.mo文件并且特定于django
def get_language_from_request(request):
"""
Analyzes the request to find what language the user wants the system to
show. Only languages listed in settings.LANGUAGES are taken into account.
If the user requests a sublanguage where we have a main language, we send
out the main language.
"""
global _accepted
from django.conf import settings
globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
supported = dict(settings.LANGUAGES)
if hasattr(request, 'session'):
lang_code = request.session.get('django_language', None)
if lang_code in supported and lang_code is not None and check_for_language(lang_code):
return lang_code
lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
if lang_code and lang_code not in supported:
lang_code = lang_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr
if lang_code and lang_code in supported and check_for_language(lang_code):
return lang_code
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in parse_accept_lang_header(accept):
if accept_lang == '*':
break
# We have a very restricted form for our language files (no encoding
# specifier, since they all must be UTF-8 and only one possible
# language each time. So we avoid the overhead of gettext.find() and
# work out the MO file manually.
# 'normalized' is the root name of the locale in POSIX format (which is
# the format used for the directories holding the MO files).
normalized = locale.locale_alias.get(to_locale(accept_lang, True))
if not normalized:
continue
# Remove the default encoding from locale_alias.
normalized = normalized.split('.')[0]
if normalized in _accepted:
# We've seen this locale before and have an MO file for it, so no
# need to check again.
return _accepted[normalized]
for lang, dirname in ((accept_lang, normalized),
(accept_lang.split('-')[0], normalized.split('_')[0])):
if lang.lower() not in supported:
continue
langfile = os.path.join(globalpath, dirname, 'LC_MESSAGES',
'django.mo')
if os.path.exists(langfile):
_accepted[normalized] = lang
return lang
return settings.LANGUAGE_CODE
是否可以为每个请求执行此操作?我想我还应该将标题设置为语言self.response.headers['Content-Language'] = language
根据我的期望,我可以直接从django获取一些功能,如果我选择使用http标题,但我不明白它的作用,所以也许你可以从django为我解释这段代码:
def parse_accept_lang_header(lang_string):
"""
Parses the lang_string, which is the body of an HTTP Accept-Language
header, and returns a list of (lang, q-value), ordered by 'q' values.
Any format errors in lang_string results in an empty list being returned.
"""
result = []
pieces = accept_language_re.split(lang_string)
if pieces[-1]:
return []
for i in range(0, len(pieces) - 1, 3):
first, lang, priority = pieces[i : i + 3]
if first:
return []
priority = priority and float(priority) or 1.0
result.append((lang, priority))
result.sort(lambda x, y: -cmp(x[1], y[1]))
return result
谢谢
我发现我无法在请求处理程序的初始化函数中使用会话,可能是因为尚未创建会话对象。所以我把用于从会话中获取语言的代码放在BaseHandler渲染函数中,它似乎起作用。考虑标头或cookie值也很好。
答案 0 :(得分:13)
这就是我的工作 - 我有一个基本请求处理程序,我的所有请求处理程序都继承,然后在这里我有一个包含可用语言的常量,我override the init method来设置每个请求的语言:
import webapp2
from webapp2_extras import i18n
AVAILABLE_LOCALES = ['en_GB', 'es_ES']
class BaseHandler(webapp2.RequestHandler):
def __init__(self, request, response):
""" Override the initialiser in order to set the language.
"""
self.initialize(request, response)
# first, try and set locale from cookie
locale = request.cookies.get('locale')
if locale in AVAILABLE_LOCALES:
i18n.get_i18n().set_locale(locale)
else:
# if that failed, try and set locale from accept language header
header = request.headers.get('Accept-Language', '') # e.g. en-gb,en;q=0.8,es-es;q=0.5,eu;q=0.3
locales = [locale.split(';')[0] for locale in header.split(',')]
for locale in locales:
if locale in AVAILABLE_LOCALES:
i18n.get_i18n().set_locale(locale)
break
else:
# if still no locale set, use the first available one
i18n.get_i18n().set_locale(AVAILABLE_LOCALES[0])
首先我检查cookie,然后检查标题,如果找不到有效的语言,最后默认为第一种语言。
要设置cookie,我有一个单独的控制器,看起来像这样:
import base
class Index(base.BaseHandler):
""" Set the language cookie (if locale is valid), then redirect back to referrer
"""
def get(self, locale):
if locale in self.available_locales:
self.response.set_cookie('locale', locale, max_age = 15724800) # 26 weeks' worth of seconds
# redirect to referrer or root
url = self.request.headers.get('Referer', '/')
self.redirect(url)
因此像www.example.com/locale/en_GB这样的网址会将区域设置更改为en_GB,设置Cookie并返回引荐来源(这样可以在任何页面上切换语言,并让它保持不变在同一页上。)
此方法没有考虑标题中区域设置的部分匹配,例如“en”而不是“en_GB”,但看到我在应用中启用的语言列表是固定的(并且区域设置更改URL在页脚中是硬编码的,我不是太担心它。
HTH
答案 1 :(得分:5)
完全基于fishwebby的回答以及一些改进和一些设计变更,这就是我的所作所为:
"""
Use this handler instead of webapp2.RequestHandler to support localization.
Fill the AVAILABLE_LOCALES tuple with the acceptable locales.
"""
__author__ = 'Cristian Perez <http://cpr.name>'
import webapp2
from webapp2_extras import i18n
AVAILABLE_LOCALES = ('en_US', 'es_ES', 'en', 'es')
class LocalizedHandler(webapp2.RequestHandler):
def set_locale_from_param(self):
locale = self.request.get('locale')
if locale in AVAILABLE_LOCALES:
i18n.get_i18n().set_locale(locale)
# Save locale to cookie for future use
self.save_locale_to_cookie(locale)
return True
return False
def set_locale_from_cookie(self):
locale = self.request.cookies.get('locale')
if locale in AVAILABLE_LOCALES:
i18n.get_i18n().set_locale(locale)
return True
return False
def set_locale_from_header(self):
locale_header = self.request.headers.get('Accept-Language') # e.g. 'es,en-US;q=0.8,en;q=0.6'
if locale_header:
locale_header = locale_header.replace(' ', '')
# Extract all locales and their preference (q)
locales = [] # e.g. [('es', 1.0), ('en-US', 0.8), ('en', 0.6)]
for locale_str in locale_header.split(','):
locale_parts = locale_str.split(';q=')
locale = locale_parts[0]
if len(locale_parts) > 1:
locale_q = float(locale_parts[1])
else:
locale_q = 1.0
locales.append((locale, locale_q))
# Sort locales according to preference
locales.sort(key=lambda locale_tuple: locale_tuple[1], reverse=True)
# Find first exact match
for locale in locales:
for available_locale in AVAILABLE_LOCALES:
if locale[0].replace('-', '_').lower() == available_locale.lower():
i18n.get_i18n().set_locale(available_locale)
return True
# Find first language match (prefix e.g. 'en' for 'en-GB')
for locale in locales:
for available_locale in AVAILABLE_LOCALES:
if locale[0].split('-')[0].lower() == available_locale.lower():
i18n.get_i18n().set_locale(available_locale)
return True
# There was no match
return False
def set_locale_default(self):
i18n.get_i18n().set_locale(AVAILABLE_LOCALES[0])
def save_locale_to_cookie(self, locale):
self.response.set_cookie('locale', locale)
def __init__(self, request, response):
"""
Override __init__ in order to set the locale
Based on: http://stackoverflow.com/a/8522855/423171
"""
# Must call self.initialze when overriding __init__
# http://webapp-improved.appspot.com/guide/handlers.html#overriding-init
self.initialize(request, response)
# First, try to set locale from GET parameter (will save it to cookie)
if not self.set_locale_from_param():
# Second, try to set locale from cookie
if not self.set_locale_from_cookie():
# Third, try to set locale from Accept-Language header
if not self.set_locale_from_header():
# Fourth, set locale to first available option
self.set_locale_default()
它检查网址中的 locale
参数,以及是否
它退出,它设置一个cookie与该语言环境以供将来使用。在那里面
您可以使用locale
在任何地方更改区域设置的方式
参数,但仍然避免即将到来的请求中的参数。
如果没有参数,则会检查 locale
Cookie 。
如果没有Cookie,则会检查 Accept-Language
标题。非常重要的是,它会考虑标题的q
preference factor并执行一些小的魔术:接受语言前缀。例如,如果浏览器指定en-GB
但AVAILABLE_LOCALES
元组中不存在,则en
将被选中(如果存在),默认情况下将使用en_US
如果en
的区域设置不存在。它还会处理大小写和格式(-
或_
作为分隔符)。