Beispiel #1
0
 def test_uselocale(self):
     """Test that uselocale does what it says on the tin."""
     with uselocale('en-US'):
         eq_(get_language(), 'en-us')
     with uselocale('de'):
         eq_(get_language(), 'de')
     with uselocale('fr'):
         eq_(get_language(), 'fr')
 def test_uselocale(self):
     """Test that uselocale does what it says on the tin."""
     with uselocale("en-US"):
         eq_(get_language(), "en-us")
     with uselocale("de"):
         eq_(get_language(), "de")
     with uselocale("fr"):
         eq_(get_language(), "fr")
 def test_uselocale(self):
     """Test that uselocale does what it says on the tin."""
     with uselocale('en-US'):
         eq_(get_language(), 'en-us')
     with uselocale('de'):
         eq_(get_language(), 'de')
     with uselocale('fr'):
         eq_(get_language(), 'fr')
    def test_mocked_gettext(self):
        """I'm not entirely sure about the mocking, so test that."""
        # Import translation now so it is affected by the mock.
        from django.utils.translation import ugettext as _

        with uselocale("en-US"):
            eq_(_("Hello"), "Hello")
        with uselocale("fr"):
            eq_(_("Hello"), "Bonjour")
        with uselocale("es"):
            eq_(_("Hello"), "Hola")
Beispiel #5
0
    def test_mocked_gettext(self):
        """I'm not entirely sure about the mocking, so test that."""
        # Import tower now so it is affected by the mock.
        from tower import ugettext as _

        with uselocale('en-US'):
            eq_(_('Hello'), 'Hello')
        with uselocale('fr'):
            eq_(_('Hello'), 'Bonjour')
        with uselocale('es'):
            eq_(_('Hello'), 'Hola')
    def test_mocked_gettext(self):
        """I'm not entirely sure about the mocking, so test that."""
        # Import tower now so it is affected by the mock.
        from tower import ugettext as _

        with uselocale('en-US'):
            eq_(_('Hello'), 'Hello')
        with uselocale('fr'):
            eq_(_('Hello'), 'Bonjour')
        with uselocale('es'):
            eq_(_('Hello'), 'Hola')
Beispiel #7
0
def geoip_suggestion(request):
    """
    Ajax view to return the localized text for GeoIP locale change suggestion.

    Takes one parameter from the querystring:

        * locales - a form encoded list of locales to translate to.

    Example url: /localize?locales[]=es&locales[]=en-US
    """
    locales = request.GET.getlist("locales[]")

    response = {"locales": {}}
    for locale in locales:
        # English and native names for the language
        response["locales"][locale] = LOCALES.get(locale, "")
        with uselocale(locale):
            # This is using our JS-style string formatting.
            response[locale] = {
                "suggestion":
                _("Would you like to view this page in "
                  "%(language)s instead?"),
                "confirm":
                _("Yes"),
                "cancel":
                _("No"),
            }

    return HttpResponse(json.dumps(response), content_type="application/json")
Beispiel #8
0
def geoip_suggestion(request):
    """
    Ajax view to return the localized text for GeoIP locale change suggestion.

    Takes one parameter from the querystring:

        * locales - a form encoded list of locales to translate to.

    Example url: /localize?locales[]=es&locales[]=en-US
    """
    locales = request.GET.getlist('locales[]')

    response = {'locales': {}}
    for locale in locales:
        # English and native names for the language
        response['locales'][locale] = LOCALES.get(locale, '')
        with uselocale(locale):
            # This is using our JS-style string formatting.
            response[locale] = {
                'suggestion':
                _('Would you like to view this page in '
                  '%(language)s instead?'),
                'confirm':
                _('Yes'),
                'cancel':
                _('No'),
            }

    return HttpResponse(json.dumps(response), content_type='application/json')
Beispiel #9
0
def geoip_suggestion(request):
    """
    Ajax view to return the localized text for GeoIP locale change suggestion.

    Takes one parameter from the querystring:

        * locales - a form encoded list of locales to translate to.

    Example url: /localize?locales[]=es&locales[]=en-US
    """
    locales = request.GET.getlist('locales[]')

    response = {'locales': {}}
    for locale in locales:
        # English and native names for the language
        response['locales'][locale] = LOCALES[locale]
        with uselocale(locale):
            # This is using our JS-style string formatting.
            response[locale] = {
                'suggestion': _('Would you like to view this page in '
                                '%(language)s instead?'),
                'confirm': _('Yes'),
                'cancel': _('No'),
            }

    return HttpResponse(json.dumps(response), content_type='application/json')
Beispiel #10
0
    def to_native(self, value):
        value = super(LocalizedCharField, self).from_native(value)
        locale = self.context.get('locale')

        if locale is None:
            return value
        with uselocale(locale):
            return _(value, self.l10n_context)
Beispiel #11
0
    def to_native(self, value):
        value = super(LocalizedCharField, self).from_native(value)
        locale = self.context.get('locale')

        if locale is None:
            return value
        with uselocale(locale):
            return _(value, self.l10n_context)
Beispiel #12
0
    def wrapper(locale, *args, **kwargs):
        try:
            with uselocale(locale):
                return f(locale, *args, **kwargs)
        except (TypeError, KeyError, ValueError, IndexError):
            # Types of errors, and examples.
            #
            # TypeError: Not enough arguments for string
            #   '%s %s %s' % ('foo', 'bar')
            # KeyError: Bad variable name
            #   '%(Foo)s' % {'foo': 10} or '{Foo}'.format(foo=10')
            # ValueError: Incomplete Format, or bad format string.
            #    '%(foo)a' or '%(foo)' or '{foo'
            # IndexError: Not enough arguments for .format() style string.
            #    '{0} {1}'.format(42)
            log.exception('Bad translation in locale "%s"', locale)

            with uselocale(settings.WIKI_DEFAULT_LANGUAGE):
                return f(settings.WIKI_DEFAULT_LANGUAGE, *args, **kwargs)
Beispiel #13
0
def wiki_to_html(wiki_markup, locale=settings.WIKI_DEFAULT_LANGUAGE, doc_id=None, parser_cls=None):
    """Wiki Markup -> HTML with the wiki app's enhanced parser"""
    if parser_cls is None:
        parser_cls = WikiParser

    with uselocale(locale):
        content = parser_cls(doc_id=doc_id).parse(
            wiki_markup, show_toc=False, locale=locale, toc_string=_("Table of Contents"),
        )
    return content
Beispiel #14
0
    def wrapper(locale, *args, **kwargs):
        try:
            with uselocale(locale):
                return f(locale, *args, **kwargs)
        except (TypeError, KeyError, ValueError, IndexError):
            # Types of errors, and examples.
            #
            # TypeError: Not enough arguments for string
            #   '%s %s %s' % ('foo', 'bar')
            # KeyError: Bad variable name
            #   '%(Foo)s' % {'foo': 10} or '{Foo}'.format(foo=10')
            # ValueError: Incomplete Format, or bad format string.
            #    '%(foo)a' or '%(foo)' or '{foo'
            # IndexError: Not enough arguments for .format() style string.
            #    '{0} {1}'.format(42)
            log.exception('Bad translation in locale "%s"', locale)

            with uselocale(settings.WIKI_DEFAULT_LANGUAGE):
                return f(settings.WIKI_DEFAULT_LANGUAGE, *args, **kwargs)
Beispiel #15
0
def wiki_to_html(wiki_markup, locale=settings.WIKI_DEFAULT_LANGUAGE,
                 doc_id=None, parser_cls=None):
    """Wiki Markup -> HTML with the wiki app's enhanced parser"""
    if parser_cls is None:
        parser_cls = WikiParser

    with statsd.timer('wiki.render'):
        with uselocale(locale):
            content = parser_cls(doc_id=doc_id).parse(
                wiki_markup, show_toc=False, locale=locale,
                toc_string=_('Table of Contents'))
    return content
Beispiel #16
0
def build_kb_bundles(products=('firefox-os', 'firefox', 'mobile')):
    redis = redis_client('default')

    if not redis:
        raise IOError('Redis not available. Cannot generate offline bundles.')

    start_time = time.time()
    size = 0

    products = [Product.objects.get(slug=p) for p in products]
    with statsd.timer('offline.build_kb_bundles.time_elapsed'):
        for locale in settings.SUMO_LANGUAGES:
            for product in products:
                with uselocale(locale):
                    bundle = merge_bundles(bundle_for_product(product, locale))

                size += len(
                    insert_bundle_into_redis(redis, product.slug, locale,
                                             bundle)[0])

    time_taken = time.time() - start_time
    log.info('Generated all offline bundles. '
             'Size: {0}. Took {1} seconds'.format(size, time_taken))
Beispiel #17
0
def build_kb_bundles(products=('firefox-os', 'firefox', 'mobile')):
    redis = redis_client('default')

    if not redis:
        raise IOError('Redis not available. Cannot generate offline bundles.')

    start_time = time.time()
    size = 0

    products = [Product.objects.get(slug=p) for p in products]
    with statsd.timer('offline.build_kb_bundles.time_elapsed'):
        for locale in settings.SUMO_LANGUAGES:
            for product in products:
                with uselocale(locale):
                    bundle = merge_bundles(bundle_for_product(product, locale))

                size += len(insert_bundle_into_redis(redis,
                                                     product.slug,
                                                     locale,
                                                     bundle)[0])

    time_taken = time.time() - start_time
    log.info('Generated all offline bundles. '
             'Size: {0}. Took {1} seconds'.format(size, time_taken))