我们可以在webapp2中使用i18n进行全局设置吗?

时间:2012-06-05 15:00:26

标签: python google-app-engine webapp2

我有一个类别列表,我想将它与i18n一起使用,以便我可以通过语言环境更改语言。

我的python代码如下:

from webapp2_extras import i18n

category_list = {}
category_list['bikes'] = {'value': i18n.gettext('CATEGORY_BIKES')}

class CategoriesHandler(BaseHandler):
    """List categories"""
    def get(self, **kwargs):
        """List all categories"""
        self.response.write(self.json_output(category_list))

它会导致错误:

  File "/Users/user/Developer/GAE/project/CategoriesHandler.py", line 11, in <module>
    category_list['bikes'] = {'value': i18n.gettext('CATEGORY_BIKES')}
  File "/Users/user/Developer/GAE/project/webapp2_extras/i18n.py", line 713, in gettext
    return get_i18n().gettext(string, **variables)
  File "/Users/user/Developer/GAE/project/webapp2_extras/i18n.py", line 894, in get_i18n
    request = request or webapp2.get_request()
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1720, in get_request
    assert getattr(_local, 'request', None) is not None, _get_request_error
AssertionError: Request global variable is not set.

但是,如果我将category_list移动​​到类get方法中,一切都很好。

class CategoriesHandler(BaseHandler):
    """List categories"""
    def get(self, **kwargs):
        """List all categories"""
        category_list = {}
        category_list['bikes'] = {'value': i18n.gettext('CATEGORY_BIKES')}
        self.response.write(self.json_output(category_list))
        pass

问题是我需要将category_list分隔到另一个配置文件,以便我可以轻松维护我的代码。有什么方法可以解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:3)

请尝试使用gettext_lazy,直到稍后(当您还知道要翻译的语言时)才会进行实际的翻译查找。

一个非常常见的惯例是

from webapp2_extras.i18n import _lazy as _
category_list['bikes'] = {'value': _('CATEGORY_BIKES')}