def test_unknown(self): """ Test that when the current locale is not supported by Babel, it defaults to en-US. """ activate('fy') eq_(Locale('en', 'US'), current_locale())
def process_request(self, request): prefixer = Prefixer(request) set_url_prefixer(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from the query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), v) for k, v in request.GET.iteritems() if k != 'lang') return HttpResponsePermanentRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = '%s?%s' % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale old_locale = prefixer.locale new_locale, _ = split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path request.locale = prefixer.locale tower.activate(prefixer.locale)
def process_request(self, request): prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if self._is_lang_change(request): # Blank out the locale so that we can set a new one. Remove lang # from the query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') return HttpResponsePermanentRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = '?'.join( [full_path, force_text(query_string, errors='ignore')]) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale old_locale = prefixer.locale new_locale, _ = urlresolvers.split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path request.locale = prefixer.locale tower.activate(prefixer.locale)
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if "lang" in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = "" new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop("lang") return HttpResponsePermanentRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get("QUERY_STRING", "") full_path = urllib.quote(full_path.encode("utf-8")) if query_string: full_path = "%s?%s" % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale. old_locale = prefixer.locale new_locale, _, _ = prefixer.split_path(full_path) if old_locale != new_locale: response["Vary"] = "Accept-Language" return response request.path_info = "/" + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app) request.LANG = prefixer.locale
def send_group_email(announcement_id): """Build and send the announcement emails to a group.""" try: announcement = Announcement.objects.get(pk=announcement_id) except Announcement.DoesNotExist: return connection = get_connection(fail_silently=True) connection.open() group = announcement.group users = User.objects.filter(groups__in=[group]) plain_content = bleach.clean(announcement.content_parsed, tags=[], strip=True).strip() email_kwargs = {'content': plain_content, 'domain': Site.objects.get_current().domain} template = 'announcements/email/announcement.ltxt' try: for u in users: # Localize email each time. activate(u.profile.locale or settings.LANGUAGE_CODE) subject = _('New announcement for {group}').format( group=group.name) message = loader.render_to_string(template, email_kwargs) m = EmailMessage(subject, message, settings.NOTIFICATIONS_FROM_ADDRESS, [u.email]) connection.send_messages([m]) finally: activate(settings.LANGUAGE_CODE) connection.close()
def _pre_setup(self): # Add the models to the db. self._original_installed_apps = list(settings.INSTALLED_APPS) for app in self.apps: settings.INSTALLED_APPS.append(app) loading.cache.loaded = False call_command('syncdb', interactive=False, verbosity=0) call_command('update_badges', verbosity=0) badger.autodiscover() if get_url_prefix: # If we're in funfactoryland, make sure a locale prefix is # set for urlresolvers locale = 'en-US' self.old_prefix = get_url_prefix() self.old_locale = get_language() rf = RequestFactory() set_url_prefix(Prefixer(rf.get('/%s/' % (locale,)))) activate(locale) # Create a default user for tests self.user_1 = self._get_user(username="******", email="*****@*****.**", password="******") # Call the original method that does the fixtures etc. super(test.TestCase, self)._pre_setup()
def test_activation_locale_detect(self): p = self._profile() # Activate french and check if the locale was set correctly tower.activate('fr') u = RegisterProfile.objects.activate_profile(p.activation_key) eq_(u.get_profile().locale, 'fr')
def process_request(self, request): prefixer = Prefixer(request) set_url_prefixer(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if "lang" in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from the query params so we don't have an infinite loop. prefixer.locale = "" new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), v) for k, v in request.GET.iteritems() if k != "lang") return HttpResponseRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get("QUERY_STRING", "") full_path = urllib.quote(full_path.encode("utf-8")) if query_string: full_path = "%s?%s" % (full_path, query_string) response = HttpResponseRedirect(full_path) # Vary on Accept-Language if we changed the locale old_locale = prefixer.locale new_locale, _ = split_path(full_path) if old_locale != new_locale: response["Vary"] = "Accept-Language" return response request.path_info = "/" + prefixer.shortened_path request.LANGUAGE_CODE = prefixer.locale tower.activate(prefixer.locale)
def _switch_locale(self): if self.source_locale: lang = self.source_locale else: lang = self.addon.default_locale tower.activate(lang) return Locale(translation.to_locale(lang))
def process_request(self, request): a_l = get_accept_language(request) lang, ov_lang = a_l, '' stored_lang, stored_ov_lang = '', '' remembered = request.COOKIES.get('lang') if remembered: chunks = remembered.split(',')[:2] stored_lang = chunks[0] try: stored_ov_lang = chunks[1] except IndexError: pass if stored_lang.lower() in settings.LANGUAGE_URL_MAP: lang = stored_lang if stored_ov_lang.lower() in settings.LANGUAGE_URL_MAP: ov_lang = stored_ov_lang if 'lang' in request.REQUEST: # `get_language` uses request.GET['lang'] and does safety checks. ov_lang = a_l lang = Prefixer(request).get_language() elif a_l != ov_lang: # Change if Accept-Language differs from Overridden Language. lang = a_l ov_lang = '' # Update cookie if values have changed. if lang != stored_lang or ov_lang != stored_ov_lang: request.LANG_COOKIE = ','.join([lang, ov_lang]) request.LANG = lang tower.activate(lang)
def test_no_activate(self, mock_activate): """If lang is Falsy, do not call activate.""" activate('fr') eq_(get_language(), 'fr') with use_lang(None): eq_(get_language(), 'fr') eq_(get_language(), 'fr') ok_(not mock_activate.called)
def test_basic(self): """ Test that translating a string works and doesn't change the current locale. """ activate('fr') eq_(_locale('message', 'xxx'), 'translated') eq_(get_language(), 'fr')
def test_babel_number(self): number = 1000000 activate('en-US') eq_(babel_number(number), u'1,000,000') activate('fr') # \xa0 is a non-breaking space eq_(babel_number(number), u'1\xa0000\xa0000')
def test_no_install_jinja_translations(): """ Setting `TOWER_INSTALL_JINJA_TRANSLATIONS` to False should skip setting the gettext and ngettext functions in the Jinja2 environment. """ jingo.env.install_null_translations() tower.activate('xx') ok_(jingo.env.globals['gettext'] != _)
def ugettext_locale(message, locale): """Translate a message in a specific locale.""" old_locale = get_language() tower.activate(locale) text = tower.ugettext(message) tower.activate(old_locale) return text
def _activate_lang(self): tower.activate(self.lang) lang = translation.get_language() if lang in charsets: self.encoding = charsets[lang] elif lang[:2] in charsets: self.encoding = charsets[lang[:2]] else: self.encoding = settings.DEFAULT_CHARSET
def test_babel_date(self): date = datetime(2011, 9, 23) activate('en-US') eq_(babel_date(date, 'short'), '9/23/11') eq_(babel_date(date, 'medium'), 'Sep 23, 2011') activate('fr') eq_(babel_date(date, 'short'), '23/09/11') eq_(babel_date(date, 'medium'), '23 sept. 2011')
def use_lang(lang): """Temporarily use another language for translation.""" if not lang: yield else: current_lang = get_language() activate(lang) yield activate(current_lang)
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), v) for k, v in request.GET.items() if k not in ('lang', 'locale-only')) response = HttpResponsePermanentRedirect( urlparams(new_path, **query)) xenophobia = 0 # User checked a box is the only reason this would happen. if 'locale-only' in request.GET: xenophobia = 1 response.set_cookie('locale-only', xenophobia, expires=NEXT_YEAR) return response if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = "%s?%s" % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale. old_locale = prefixer.locale new_locale, _, _ = prefixer.split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app) request.LANG = prefixer.locale if 'locale-only' in request.COOKIES: request.XENOPHOBIA = (request.COOKIES['locale-only'] == '1') else: try: conf = Config.objects.get(pk='xenophobia') request.XENOPHOBIA = conf.json.get( translation.get_language(), False) except Config.DoesNotExist: request.XENOPHOBIA = False
def activate_lang(self): """ Activate the language for the user. If none is set will go to the site default which is en-US. """ lang = self.lang if self.lang else settings.LANGUAGE_CODE old = translation.get_language() tower.activate(lang) yield tower.activate(old)
def activate(self, locale): """Context manager that temporarily activates a locale.""" old_prefix = get_url_prefix() old_locale = get_language() rf = test_utils.RequestFactory() set_url_prefix(Prefixer(rf.get('/%s/' % (locale,)))) activate(locale) yield set_url_prefix(old_prefix) activate(old_locale)
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) if settings.DEBUG: redirect_type = HttpResponseRedirect else: redirect_type = HttpResponsePermanentRedirect urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) # In mkt, don't vary headers on User-Agent. with_app = not getattr(settings, 'MARKETPLACE', False) if (prefixer.app == amo.MOBILE.short and request.path.rstrip('/').endswith('/' + amo.MOBILE.short)): # TODO: Eventually put MOBILE in RETIRED_APPS, but not yet. return redirect_type(request.path.replace('/mobile', '/android')) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') return redirect_type(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = "%s?%s" % (full_path, query_string) response = redirect_type(full_path) # Cache the redirect for a year. if not settings.DEBUG: patch_cache_control(response, max_age=60 * 60 * 24 * 365) # Vary on Accept-Language or User-Agent if we changed the locale or # app. old_app = prefixer.app old_locale = prefixer.locale new_locale, new_app, _ = prefixer.split_path(full_path) if old_locale != new_locale: patch_vary_headers(response, ['Accept-Language']) if with_app and old_app != new_app: patch_vary_headers(response, ['User-Agent']) return response request.path_info = '/' + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app, amo.FIREFOX) request.LANG = prefixer.locale
def process_request(self, request): self.locale_from_accept = False if "lang" in request.GET: locale = self.find_from_input(request.GET["lang"]) else: locale = self.get_language(request) if locale: self.locale_from_accept = True # TODO(Kumar) set/check cookie? request.locale = locale tower.activate(locale)
def _post_teardown(self): # Call the original method. super(test.TestCase, self)._post_teardown() # Restore the settings. settings.INSTALLED_APPS = self._original_installed_apps loading.cache.loaded = False if get_url_prefix: # If we're in funfactoryland, back out of the locale tweaks set_url_prefix(self.old_prefix) activate(self.old_locale)
def test_activate_with_override_settings_and_django_14(): # Django 1.4 includes a handy override_settings helper. When you # use that, it must not include SETTINGS_MODULE in the settings. # This tests that activating a locale doesn't throw an # AssertionError because there's no SETTINGS_MODULE in settings. if django.VERSION >= (1, 4): from django.test.utils import override_settings with override_settings(): tower.deactivate_all() tower.activate('xx') # String is the same because it couldn't find # SETTINGS_MODULE and thus didn't pick up the right .mo # files. eq_(_('this is a test'), 'this is a test') tower.deactivate_all()
def legend(locale=None): """ Legend of error message codes for developers. These codes are used in validation but will be slightly hidden from users so as not to cause confusion. The legend is a reference for developers. """ old_locale = translation.get_language() if locale: tower.activate(locale) try: return _build_legend() finally: tower.activate(old_locale)
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) redirect_type = HttpResponsePermanentRedirect if settings.MARKETPLACE: # Force en-US until we localize Marketplace. prefixer.locale = 'en-US' # Use 302 redirects if these URLs are gonna change. redirect_type = redirect urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') return redirect_type(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = "%s?%s" % (full_path, query_string) response = redirect_type(full_path) # Cache the redirect for a year. But not for Marketplace! if not (settings.DEBUG or settings.MARKETPLACE): patch_cache_control(response, max_age=60 * 60 * 24 * 365) # Vary on Accept-Language or User-Agent if we changed the locale or # app. old_app = prefixer.app old_locale = prefixer.locale new_locale, new_app, _ = prefixer.split_path(full_path) if old_locale != new_locale: patch_vary_headers(response, ['Accept-Language']) if old_app != new_app: patch_vary_headers(response, ['User-Agent']) return response request.path_info = '/' + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app, amo.FIREFOX) request.LANG = prefixer.locale
def process_request(self, request): request.LANG = settings.LANGUAGE_CODE remembered = request.COOKIES.get('lang', '').lower() if remembered in settings.LANGUAGE_URL_MAP: request.LANG = settings.LANGUAGE_URL_MAP[remembered] user_defined = Prefixer(request).get_language() if ('lang' in request.GET or not remembered or user_defined != settings.LANGUAGE_CODE): request.LANG = user_defined if not remembered or remembered != request.LANG: request.set_cookie('lang', request.LANG) tower.activate(request.LANG)
def activate(self, locale=None, app=None): """Active an app or a locale.""" prefixer = old_prefix = get_url_prefix() old_app = old_prefix.app old_locale = translation.get_language() if locale: rf = RequestFactory() prefixer = Prefixer(rf.get('/%s/' % (locale,))) tower.activate(locale) if app: prefixer.app = app set_url_prefix(prefixer) yield old_prefix.app = old_app set_url_prefix(old_prefix) tower.activate(old_locale)
def test_get_services_in_ja_locale(): testo = sharing.LOCALSERVICE1 testo.shortname = 'translated-localservice1' expected = [ 'digg', 'facebook', 'delicious', 'myspace', 'friendfeed', 'twitter', 'translated-localservice1' ] with patch.object(sharing, 'LOCALSERVICE1', testo): old_locale = translation.get_language() try: tower.activate('ja') assert expected == [s.shortname for s in sharing.get_services()] finally: tower.activate(old_locale)
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) redirect_type = HttpResponsePermanentRedirect urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) # In mkt, don't vary headers on User-Agent. with_app = not getattr(settings, 'MARKETPLACE', False) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') return redirect_type(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = "%s?%s" % (full_path, query_string) response = redirect_type(full_path) # Cache the redirect for a year. if not settings.DEBUG: patch_cache_control(response, max_age=60 * 60 * 24 * 365) # Vary on Accept-Language or User-Agent if we changed the locale or # app. old_app = prefixer.app old_locale = prefixer.locale new_locale, new_app, _ = prefixer.split_path(full_path) if old_locale != new_locale: patch_vary_headers(response, ['Accept-Language']) if with_app and old_app != new_app: patch_vary_headers(response, ['User-Agent']) return response request.path_info = '/' + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app, amo.FIREFOX) request.LANG = prefixer.locale
def send_pending_membership_emails(): """ For each curated group that has pending memberships that the curators have not yet been emailed about, send to all the curators an email with the count of all pending memberships and a link to view and manage the requests. """ Group = get_model('groups', 'Group') GroupMembership = get_model('groups', 'GroupMembership') # Curated groups that have pending membership requests groups = Group.objects.exclude(curators__isnull=True) groups = groups.filter( groupmembership__status=GroupMembership.PENDING).distinct() for group in groups: # what's the max pk of pending memberships? pending_memberships = group.groupmembership_set.filter( status=GroupMembership.PENDING) max_pk = pending_memberships.aggregate(max_pk=Max('pk'))['max_pk'] # Only send reminder if there are newer requests than we'd previously reminded about if max_pk > group.max_reminder: # TODO: Switch locale to curator's preferred language so translation will occur # Using English for now tower.activate('en-us') count = pending_memberships.count() subject = tower.ungettext( '%(count)d outstanding request to join Mozillians group "%(name)s"', '%(count)d outstanding requests to join Mozillians group "%(name)s"', count) % { 'count': count, 'name': group.name } body = render_to_string('groups/email/memberships_pending.txt', { 'group': group, 'count': count, }) send_mail(subject, body, settings.FROM_NOREPLY, [profile.user.email for profile in group.curators.all()], fail_silently=False) group.max_reminder = max_pk group.save()
def test_mkt_locale_not_in_django(): """ We load gettext catalogs in this order: django/locale/django.po locale/messages.po If Django doesn't have a locale, it returns the en-us catalog as a fallback. But then we take that catalog and merge in our messages.po. That's no good because we just mixed some other locale into en-us. This test will be invalid once Django gets an mn locale. """ tower.activate('mn') en = trans_real._translations['en-US'] mn = trans_real._translations['mn'] assert en != mn assert en._catalog != mn._catalog
def test_get_services_in_ja_locale(): testo = sharing.LOCALSERVICE1 testo.shortname = 'translated-localservice1' expected = [ 'digg', 'facebook', 'delicious', 'myspace', 'friendfeed', 'twitter', 'translated-localservice1'] with patch.object(sharing, 'LOCALSERVICE1', testo): tower.activate('ja') assert expected == [s.shortname for s in sharing.get_services()]
def member_removed_email(group_pk, user_pk): """ Email to member when he is removed from group """ Group = get_model('groups', 'Group') group = Group.objects.get(pk=group_pk) user = User.objects.get(pk=user_pk) tower.activate('en-us') template_name = 'groups/email/member_removed.txt' subject = _('Removed from Mozillians group "%s"') % group.name template = get_template(template_name) context = { 'group': group, 'user': user, } body = template.render(Context(context)) send_mail(subject, body, settings.FROM_NOREPLY, [user.email], fail_silently=False)
def email_membership_change(group_pk, user_pk, old_status, new_status): """ Email user that their group membership status has changed. old_status and new_status can either be a valid value for GroupMembership.status, or None if we're going from or to a state where there is no GroupMembership record (e.g. if they're being removed from a group). This is queued from Group.add_member() and Group.remove_member(). """ Group = get_model('groups', 'Group') GroupMembership = get_model('groups', 'GroupMembership') group = Group.objects.get(pk=group_pk) user = User.objects.get(pk=user_pk) # TODO: Switch locale to user's preferred language so translation will occur # Using English for now tower.activate('en-us') if old_status == GroupMembership.PENDING: if new_status == GroupMembership.MEMBER: subject = _('Accepted to Mozillians group "%s"') % group.name template_name = 'groups/email/accepted.txt' elif new_status is None: subject = _('Not accepted to Mozillians group "%s"') % group.name template_name = 'groups/email/rejected.txt' else: # Odd things happen in some of our tests. Don't worry about it. raise ValueError("BAD ARGS TO email_membership_change") else: # Odd things happen in some of our tests. Don't worry about it. raise ValueError("BAD ARGS TO email_membership_change") context = { 'group': group, 'user': user, } template = get_template(template_name) body = template.render(Context(context)) send_mail(subject, body, settings.FROM_NOREPLY, [user.email], fail_silently=False)
def process_request(self, request): prefixer = Prefixer(request) set_url_prefixer(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from the query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), v) for k, v in request.GET.iteritems() if k != 'lang') # 'lang' is only used on the language selection page. If this is # present it is safe to set language preference for the current # user. if request.user.is_anonymous(): cookie = settings.LANGUAGE_COOKIE_NAME request.session[cookie] = request.GET['lang'] return HttpResponseRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = '%s?%s' % (full_path, query_string) response = HttpResponseRedirect(full_path) # Vary on Accept-Language if we changed the locale old_locale = prefixer.locale new_locale, _ = split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path request.LANGUAGE_CODE = prefixer.locale tower.activate(prefixer.locale)
def handle_builtin(self, license): import amo # License.builtin is off by one! data = amo.LICENSE_IDS[license.builtin - 1] license.url = data.url license.on_form = data.on_form if data.icons: license.icons = ' '.join(data.icons) license.some_rights = bool(data.linktext) if data.shortname: license.text = license_text(data.shortname) # Gather all the translated names. activate('en-us') license.name = en_name = unicode(data.name) names = {} for lang in settings.AMO_LANGUAGES: activate(lang) trans = ugettext(en_name) if trans and trans != en_name: names[lang] = trans activate('en-us') license.name = names license.save()
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') return HttpResponsePermanentRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = "%s?%s" % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language or User-Agent if we changed the locale or # app. old_app = prefixer.app old_locale = prefixer.locale new_locale, new_app, _ = prefixer.split_path(full_path) if old_locale != new_locale: patch_vary_headers(response, ['Accept-Language']) if old_app != new_app: patch_vary_headers(response, ['User-Agent']) return response request.path_info = '/' + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app) request.LANG = prefixer.locale
def process_request(self, request): a_l = get_accept_language(request) lang, ov_lang = a_l, '' stored_lang, stored_ov_lang = '', '' remembered = request.COOKIES.get('lang') if remembered: chunks = remembered.split(',')[:2] stored_lang = chunks[0] try: stored_ov_lang = chunks[1] except IndexError: pass if stored_lang.lower() in settings.LANGUAGE_URL_MAP: lang = stored_lang if stored_ov_lang.lower() in settings.LANGUAGE_URL_MAP: ov_lang = stored_ov_lang if 'lang' in request.REQUEST: # `get_language` uses request.GET['lang'] and does safety checks. ov_lang = a_l lang = Prefixer(request).get_language() elif a_l != ov_lang: # Change if Accept-Language differs from Overridden Language. lang = a_l ov_lang = '' # Update cookie if values have changed. if lang != stored_lang or ov_lang != stored_ov_lang: request.LANG_COOKIE = ','.join([lang, ov_lang]) if (getattr(request, 'amo_user', None) and request.amo_user.lang != lang): request.amo_user.lang = lang request.amo_user.save() request.LANG = lang tower.activate(lang)
def process_request(self, request): a_l = lang_from_accept_header(request.META.get('HTTP_ACCEPT_LANGUAGE', '')) lang, ov_lang = a_l, '' stored_lang, stored_ov_lang = '', '' remembered = request.COOKIES.get('lang') if remembered: chunks = remembered.split(',')[:2] stored_lang = chunks[0] try: stored_ov_lang = chunks[1] except IndexError: pass if stored_lang.lower() in settings.LANGUAGE_URL_MAP: lang = stored_lang if stored_ov_lang.lower() in settings.LANGUAGE_URL_MAP: ov_lang = stored_ov_lang if 'lang' in request.REQUEST: # `get_language` uses request.GET['lang'] and does safety checks. ov_lang = a_l lang = self.get_language(request) elif a_l != ov_lang: # Change if Accept-Language differs from Overridden Language. lang = a_l ov_lang = '' # Update cookie if values have changed. if lang != stored_lang or ov_lang != stored_ov_lang: request.LANG_COOKIE = ','.join([lang, ov_lang]) if request.user.is_authenticated() and request.user.lang != lang: request.user.lang = lang request.user.save() request.LANG = lang tower.activate(lang)
def uselocale(locale): """ Context manager for setting locale and returning to previous locale. This is useful for when doing translations for things run by celery workers or out of the HTTP request handling path. Example: with uselocale('xx'): subj = _('Subject of my email') msg = render_email(email_template, email_kwargs) mail.send_mail(subj, msg, ...) In Kitsune, you can get the right locale from Profile.locale and also request.LANGUAGE_CODE. If Kitsune is handling an HTTP request already, you don't have to run uselocale---the locale will already be set correctly. """ currlocale = translation.get_language() tower.activate(locale) yield tower.activate(currlocale)
def lang_activate(locale): """ Context manager that temporarily activates a locale. This is slightly different from use_lang, as it also sets the global prefixer used by reverse to determine the locale in urls. We don't use that in non-test code because it creates a test request using Django test code. This means that use_lang does not affect reverse. We get around that with a hack of using the lang GET argument when necessary, but this really should be fixed someday. """ if not locale: yield else: old_prefix = get_url_prefix() old_locale = get_language() rf = test_utils.RequestFactory() set_url_prefix(Prefixer(rf.get('/%s/' % (locale, )))) activate(locale) yield set_url_prefix(old_prefix) activate(old_locale)
def process_request(self, request): prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) # Lang is changeable by GET request. if 'lang' in request.GET: # Blank out the prefixer attribute so that we can set a new # one. Remove the parameter from the query params so we don't # have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') return HttpResponsePermanentRedirect(urlparams(new_path, **query)) if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = '%s?%s' % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale old_locale = prefixer.locale new_locale, _ = prefixer.split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path request.locale = prefixer.locale tower.activate(prefixer.locale)
def no_translation(lang=None): """ Activate the settings lang, or lang provided, while in context. """ old_lang = translation.trans_real.get_language() if lang: tower.activate(lang) else: tower.activate(settings.LANGUAGE_CODE) yield tower.activate(old_lang)
def activate_locale(request, locale): """ Activates the specified locale if it is in the list of supported locales. """ # HACK: It's not totally clear to me where Django or tower do the matching # that equates locales like es-LA to es, and I'm scared enough of getting it # wrong to want to avoid it for the first release. So instead, we'll # activate the requested locale, and then check what locale got chosen by # django as the usable locale, and match that against our locale whitelist. # TODO: Properly filter out locales prior to calling activate. tower.activate(locale) lang = get_language() if not settings.DEV and lang not in settings.FACEBOOK_LOCALES: lang = lang.split('-')[0] tower.activate(lang) lang = get_language() if lang not in settings.FACEBOOK_LOCALES: lang = 'en-us' tower.activate(lang) request.locale = lang
def get_best_locale(locale): """ Returns the most appropriate locale from the list of supported locales. This can either be the locale itself (if it's supported), the main locale for that language if any or failing any of that the default `en-US`. Adapted from `activate_locale` in Affiliates (http://bit.ly/17if6nh). """ # Compare using lowercase locales since they become lowercase once # activated. supported_locales = [loc.lower() for loc in settings.FACEBOOK_LOCALES] # HACK: It's not totally clear to me where Django or tower do the matching # that equates locales like es-LA to es, and I'm scared enough of getting # it wrong to want to avoid it for the first release. So instead, we'll # activate the requested locale, and then check what locale got chosen by # django as the usable locale, and match that against our locale # whitelist. # TODO: Properly filter out locales prior to calling activate. old_locale = get_language() tower.activate(locale) lang = get_language() if lang.lower() not in supported_locales: # Try to activate just the language and use the resulting locale lang_prefix = lang.split('-')[0] tower.activate(lang_prefix) lang = get_language() if lang.lower() not in supported_locales: # Finally, try to find a locale with that language in the supported # locales. Otherwise, use default en-US. try: lang = next(locale for locale in settings.FACEBOOK_LOCALES if locale.startswith(lang_prefix)) except StopIteration: lang = 'en-US' tower.activate(old_locale) return lang
def mail_thankyou(self, request=None): """ Mail a thankyou note for a completed contribution. Raises a ``ContributionError`` exception when the contribution is not complete or email addresses are not found. """ # Setup l10n before loading addon. if self.source_locale: lang = self.source_locale else: lang = self.addon.default_locale tower.activate(lang) # Thankyous must be enabled. if not self.addon.enable_thankyou: # Not an error condition, just return. return # Contribution must be complete. if not self.transaction_id: raise ContributionError('Transaction not complete') # Send from support_email, developer's email, or default. from_email = settings.DEFAULT_FROM_EMAIL if self.addon.support_email: from_email = str(self.addon.support_email) else: try: author = self.addon.listed_authors[0] if author.email and not author.emailhidden: from_email = author.email except (IndexError, TypeError): # This shouldn't happen, but the default set above is still ok. pass # We need the contributor's email. to_email = self.post_data['payer_email'] if not to_email: raise ContributionError('Empty payer email') # Make sure the url uses the right language. # Setting a prefixer would be nicer, but that requires a request. url_parts = self.addon.meet_the_dev_url().split('/') url_parts[1] = lang # Buildup the email components. t = loader.get_template('stats/contribution-thankyou-email.ltxt') c = { 'thankyou_note': self.addon.thankyou_note, 'addon_name': self.addon.name, 'learn_url': '%s%s?src=emailinfo' % (settings.SITE_URL, '/'.join(url_parts)), 'domain': settings.DOMAIN, } body = t.render(Context(c)) subject = _('Thanks for contributing to {addon_name}').format( addon_name=self.addon.name) # Send the email if send_mail(subject, body, from_email, [to_email], fail_silently=True, perm_setting='dev_thanks'): # Clear out contributor identifying information. del(self.post_data['payer_email']) self.save()
def setup_yy(): tower.activate('yy')
def setup(): tower.activate('xx')
def test_basic(self): """Test that the currently locale is correctly returned.""" activate('fr') eq_(Locale('fr'), current_locale())
def tower_activate(self, region): try: activate(region) yield finally: activate('en-US')
import mkt from mkt.constants import regions from mkt.webapps.models import (update_search_index as app_update_search_index, WebappIndexer, Webapp) from mkt.webapps.tasks import unindex_webapps from mkt.site.fixtures import fixture # We might now have gettext available in jinja2.env.globals when running tests. # It's only added to the globals when activating a language with tower (which # is usually done in the middlewares). During tests, however, we might not be # running middlewares, and thus not activating a language, and thus not # installing gettext in the globals, and thus not have it in the context when # rendering templates. tower.activate('en') def formset(*args, **kw): """ Build up a formset-happy POST. *args is a sequence of forms going into the formset. prefix and initial_count can be set in **kw. """ prefix = kw.pop('prefix', 'form') total_count = kw.pop('total_count', len(args)) initial_count = kw.pop('initial_count', len(args)) data = {prefix + '-TOTAL_FORMS': total_count, prefix + '-INITIAL_FORMS': initial_count} for idx, d in enumerate(args):
def test_basic(self): activate('fr') eq_(get_language(), 'fr') with use_lang('en-us'): eq_(get_language(), 'en-us') eq_(get_language(), 'fr')
from bandwagon.models import Collection from files.models import File from lib.es.signals import process, reset from translations.hold import clean_translations from translations.models import Translation from versions.models import ApplicationsVersions, Version from users.models import RequestUser, UserProfile # We might now have gettext available in jinja2.env.globals when running tests. # It's only added to the globals when activating a language with tower (which # is usually done in the middlewares). During tests, however, we might not be # running middlewares, and thus not activating a language, and thus not # installing gettext in the globals, and thus not have it in the context when # rendering templates. tower.activate('en-us') def formset(*args, **kw): """ Build up a formset-happy POST. *args is a sequence of forms going into the formset. prefix and initial_count can be set in **kw. """ prefix = kw.pop('prefix', 'form') total_count = kw.pop('total_count', len(args)) initial_count = kw.pop('initial_count', len(args)) data = {prefix + '-TOTAL_FORMS': total_count, prefix + '-INITIAL_FORMS': initial_count} for idx, d in enumerate(args):
def process_request(self, request): prefixer = urlresolvers.Prefixer(request) tower.activate(prefixer.locale)
def test_valid_code(self): """Test the name of a language with valid language code.""" tower.activate('fr') name = langcode_to_name('en') eq_(name, u'Anglais')
def test_invalid_code(self): """Test the language name with invalid language code.""" tower.activate('fr') name = langcode_to_name('foobar') eq_(name, 'foobar')
from django.conf import settings from django.conf.urls import include, patterns, url from django.contrib import admin from django.shortcuts import render import tower from mozillians.common.monkeypatches import patch # Funfactory monkeypatches customized to work with Django 1.7 admin patch() # Activate a locale so that jinja2 doesn't choke when running a shell # or individual tests that need translation and don't involve a web # request, like when testing emails. tower.activate('en-US') def error_page(request, template, status=None): """Render error templates, found in the root /templates directory. If no status parameter is explcitedly passed, this function assumes your HTTP status code is the same as your template name (i.e. passing a template=404 will render 404.html with the HTTP status code 404). """ return render(request, '%d.html' % template, status=(status or template)) handler404 = lambda r: error_page(r, 404) handler500 = lambda r: error_page(r, 500) handler_csrf = lambda r, cb=None: error_page(r, 'csrf_error', status=400)