2012-06-05 78 views
1

我有一个类别清单,我想用国际化使用它,这样我可以通过现场改变语言。我们可以在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分离到另一个配置文件,这样我可以很容易地保持我的代码。有什么办法可以解决这个问题吗?谢谢!

回答

3

尝试gettext_lazy相反,它不会做实际的转变查找,直到后来(当你也知道你想翻译成哪种语言)。

一个非常常见的惯例是

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

伟大的答案!这解决了我的problem..but我得到了另一个问题:我需要使用json.dumps()来转换category_list到JSON对象,但似乎category_list将不再使用ugettext_lazy后JSON序列化。有什么办法可以解决这个问题吗?无论如何感谢您的回答! –

+1

制作一个默认参数传递给json.dumps的defaultencode方法。检查传入的对象是否是一个懒惰的可翻译对象,在这种情况下,如果翻译正确连接,请执行str(object)或unicode(object)。 – tesdal

+0

完美答案!我尝试过,它像魔术般运作!谢谢! –

相关问题