def get_user_locale(self): """ Tries to identify the user locale in the following order. If not found in any of them, None is returned. On returning None the browser Accept headers are used to identify the language 1. Look for the locale in the user object if user is logged in 2. Look for the locale in the cookie 3. Look for the locale in the url in the args (locale) """ # 1. Look for the locale in the cookie cookie_locale = self.get_secure_cookie('locale') if cookie_locale: return locale.get(cookie_locale) # 2. Look for the locale in the url url_locale = self.get_argument('locale', default=None) if url_locale: return locale.get(url_locale) if self.current_user is None: return None # Fallback to browser based locale detection # 3. Look for the locale in the user object if user is logged in if self.current_user and self.current_user.locale: return locale.get(self.current_user.locale) # 4. Fallback to browser based locale detection return None
def test_0010_load_gettext(self): """ Load the translations from pycountry to test """ from monstor.utils import locale locale.load_gettext_translations(pycountry.LOCALES_DIR, 'iso3166') self.assertTrue("es" in locale._supported_locales) t = locale.get("pt_BR") self.assertEqual(t.translate("United States"), u'Estados Unidos') t = locale.get("pt") self.assertEqual(t.translate("United States"), u'Estados Unidos') t = locale.get("es") self.assertEqual(t.translate("United States"), u'Estados Unidos')
def get_browser_locale(self, default="en_US"): """Determines the user's locale from Accept-Language header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = self.request.headers["Accept-Language"].split(",") locales = [] for language in languages: parts = language.strip().split(";") if len(parts) > 1 and parts[1].startswith("q="): try: score = float(parts[1][2:]) except (ValueError, TypeError): score = 0.0 else: score = 1.0 locales.append((parts[0], score)) if locales: locales.sort(key=lambda (l, s): s, reverse=True) codes = [l[0] for l in locales] return locale.get(*codes) return locale.get(default)