2012-06-05 98 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

完美答案!我嘗試過,它像魔術般運作!謝謝! –

相關問題