Search code examples
pythongoogle-app-enginewebapp2

Can we do global setting with i18n in webapp2?


I have a category list, and I'd like use it with i18n so that I can change the language by locale.

My python code is as following:

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))

And it will cause the error:

  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.

However if I move the category_list into the class get method, everything is fine.

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

The problem is that I need to separate category_list to another config file so that I can maintain my code easily. Is there any way to solve this problem? Thanks!


Solution

  • Try gettext_lazy instead, which won't do actual translation lookup until later (when you also know which language you want to translate to).

    A very common convention is

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