|
| 1 | +#!/usr/bin/env python |
| 2 | +# |
| 3 | +# Copyright 2013 Google Inc. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""A small module for i18n of webapp2 and jinja2 based apps. |
| 18 | +
|
| 19 | +The idea of this example, especially for how to translate strings in |
| 20 | +Javascript is originally from an implementation of Django i18n. |
| 21 | +""" |
| 22 | + |
| 23 | + |
| 24 | +import gettext |
| 25 | +import json |
| 26 | +import os |
| 27 | + |
| 28 | +import jinja2 |
| 29 | + |
| 30 | +import webapp2 |
| 31 | + |
| 32 | +from webob import Request |
| 33 | + |
| 34 | + |
| 35 | +def _get_plural_forms(js_translations): |
| 36 | + """Extracts the parameters for what constitutes a plural. |
| 37 | +
|
| 38 | + Args: |
| 39 | + js_translations: GNUTranslations object to be converted. |
| 40 | +
|
| 41 | + Returns: |
| 42 | + A tuple of: |
| 43 | + A formula for what constitutes a plural |
| 44 | + How many plural forms there are |
| 45 | + """ |
| 46 | + plural = None |
| 47 | + n_plural = 2 |
| 48 | + if '' in js_translations._catalog: |
| 49 | + for l in js_translations._catalog[''].split('\n'): |
| 50 | + if l.startswith('Plural-Forms:'): |
| 51 | + plural = l.split(':', 1)[1].strip() |
| 52 | + print "plural is %s" % plural |
| 53 | + if plural is not None: |
| 54 | + for raw_element in plural.split(';'): |
| 55 | + element = raw_element.strip() |
| 56 | + if element.startswith('nplurals='): |
| 57 | + n_plural = int(element.split('=', 1)[1]) |
| 58 | + elif element.startswith('plural='): |
| 59 | + plural = element.split('=', 1)[1] |
| 60 | + print "plural is now %s" % plural |
| 61 | + else: |
| 62 | + n_plural = 2 |
| 63 | + plural = '(n == 1) ? 0 : 1' |
| 64 | + return plural, n_plural |
| 65 | + |
| 66 | + |
| 67 | +def convert_translations_to_dict(js_translations): |
| 68 | + """Convert a GNUTranslations object into a dict for jsonifying. |
| 69 | +
|
| 70 | + Args: |
| 71 | + js_translations: GNUTranslations object to be converted. |
| 72 | +
|
| 73 | + Returns: |
| 74 | + A dictionary representing the GNUTranslations object. |
| 75 | + """ |
| 76 | + plural, n_plural = _get_plural_forms(js_translations) |
| 77 | + |
| 78 | + translations_dict = {'plural': plural, 'catalog': {}, 'fallback': None} |
| 79 | + if js_translations._fallback is not None: |
| 80 | + translations_dict['fallback'] = convert_translations_to_dict( |
| 81 | + js_translations._fallback |
| 82 | + ) |
| 83 | + for key, value in js_translations._catalog.items(): |
| 84 | + if key == '': |
| 85 | + continue |
| 86 | + if type(key) in (str, unicode): |
| 87 | + translations_dict['catalog'][key] = value |
| 88 | + elif type(key) == tuple: |
| 89 | + if key[0] not in translations_dict['catalog']: |
| 90 | + translations_dict['catalog'][key[0]] = [''] * n_plural |
| 91 | + translations_dict['catalog'][key[0]][int(key[1])] = value |
| 92 | + return translations_dict |
| 93 | + |
| 94 | + |
| 95 | +class BaseHandler(webapp2.RequestHandler): |
| 96 | + """A base handler for installing i18n-aware Jinja2 environment.""" |
| 97 | + |
| 98 | + @webapp2.cached_property |
| 99 | + def jinja2_env(self): |
| 100 | + """Cached property for a Jinja2 environment. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + Jinja2 Environment object. |
| 104 | + """ |
| 105 | + |
| 106 | + jinja2_env = jinja2.Environment( |
| 107 | + loader=jinja2.FileSystemLoader( |
| 108 | + os.path.join(os.path.dirname(__file__), 'templates')), |
| 109 | + extensions=['jinja2.ext.i18n']) |
| 110 | + jinja2_env.install_gettext_translations( |
| 111 | + self.request.environ['i18n_utils.active_translation']) |
| 112 | + jinja2_env.globals['get_i18n_js_tag'] = self.get_i18n_js_tag |
| 113 | + return jinja2_env |
| 114 | + |
| 115 | + def get_i18n_js_tag(self): |
| 116 | + """Generates a Javascript tag for i18n in Javascript. |
| 117 | +
|
| 118 | + This instance method is installed to the global namespace of |
| 119 | + the Jinja2 environment, so you can invoke this method just |
| 120 | + like `{{ get_i18n_js_tag() }}` from anywhere in your Jinja2 |
| 121 | + template. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + A 'javascript' HTML tag which contains functions and |
| 125 | + translation messages for i18n. |
| 126 | + """ |
| 127 | + |
| 128 | + template = self.jinja2_env.get_template('javascript_tag.jinja2') |
| 129 | + return template.render({'javascript_body': self.get_i18n_js()}) |
| 130 | + |
| 131 | + def get_i18n_js(self): |
| 132 | + """Generates a Javascript body for i18n in Javascript. |
| 133 | +
|
| 134 | + If you want to load these javascript code from a static HTML |
| 135 | + file, you need to create another handler which just returns |
| 136 | + the code generated by this function. |
| 137 | +
|
| 138 | + Returns: |
| 139 | + Actual javascript code for functions and translation |
| 140 | + messages for i18n. |
| 141 | + """ |
| 142 | + |
| 143 | + try: |
| 144 | + js_translations = gettext.translation( |
| 145 | + 'jsmessages', 'locales', fallback=False, |
| 146 | + languages=self.request.environ[ |
| 147 | + 'i18n_utils.preferred_languages'], |
| 148 | + codeset='utf-8') |
| 149 | + except IOError: |
| 150 | + template = self.jinja2_env.get_template('null_i18n_js.jinja2') |
| 151 | + return template.render() |
| 152 | + |
| 153 | + translations_dict = convert_translations_to_dict(js_translations) |
| 154 | + template = self.jinja2_env.get_template('i18n_js.jinja2') |
| 155 | + return template.render( |
| 156 | + {'translations': json.dumps(translations_dict, indent=1)}) |
| 157 | + |
| 158 | + |
| 159 | +class I18nMiddleware(object): |
| 160 | + """A WSGI middleware for i18n. |
| 161 | +
|
| 162 | + This middleware determines users' preferred language, loads the |
| 163 | + translations files, and install it to the builtin namespace of the |
| 164 | + Python runtime. |
| 165 | + """ |
| 166 | + |
| 167 | + def __init__(self, app, default_language='en', locale_path=None): |
| 168 | + """A constructor for this middleware. |
| 169 | +
|
| 170 | + Args: |
| 171 | + app: A WSGI app that you want to wrap with this |
| 172 | + middleware. |
| 173 | + default_language: fallback language; ex: 'en', 'ja', etc. |
| 174 | + locale_path: A directory containing the translations |
| 175 | + file. (defaults to 'locales' directory) |
| 176 | + """ |
| 177 | + |
| 178 | + self.app = app |
| 179 | + if locale_path is None: |
| 180 | + locale_path = os.path.join( |
| 181 | + os.path.abspath(os.path.dirname(__file__)), 'locales') |
| 182 | + self.locale_path = locale_path |
| 183 | + self.default_language = default_language |
| 184 | + |
| 185 | + def __call__(self, environ, start_response): |
| 186 | + """Called by WSGI when a request comes in. |
| 187 | +
|
| 188 | + Args: |
| 189 | + environ: A dict holding environment variables. |
| 190 | + start_response: A WSGI callable (PEP333). |
| 191 | +
|
| 192 | + Returns: |
| 193 | + Application response data as an iterable. It just returns |
| 194 | + the return value of the inner WSGI app. |
| 195 | + """ |
| 196 | + req = Request(environ) |
| 197 | + preferred_languages = list(req.accept_language) |
| 198 | + if self.default_language not in preferred_languages: |
| 199 | + preferred_languages.append(self.default_language) |
| 200 | + translation = gettext.translation( |
| 201 | + 'messages', self.locale_path, fallback=True, |
| 202 | + languages=preferred_languages, codeset='utf-8') |
| 203 | + translation.install(unicode=True, names=['gettext', 'ngettext']) |
| 204 | + environ['i18n_utils.active_translation'] = translation |
| 205 | + environ['i18n_utils.preferred_languages'] = preferred_languages |
| 206 | + |
| 207 | + return self.app(environ, start_response) |
0 commit comments