예제 #1
0
 def test_deprecation(self):
     reset_warning_registry()
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         text.javascript_quote('thingy')
         self.assertEqual(len(w), 1)
         self.assertIn('escapejs()', repr(w[0].message))
예제 #2
0
파일: i18n.py 프로젝트: RaoUmer/django
def get_formats():
    """
    Returns all formats strings required for i18n to work
    """
    FORMAT_SETTINGS = (
        "DATE_FORMAT",
        "DATETIME_FORMAT",
        "TIME_FORMAT",
        "YEAR_MONTH_FORMAT",
        "MONTH_DAY_FORMAT",
        "SHORT_DATE_FORMAT",
        "SHORT_DATETIME_FORMAT",
        "FIRST_DAY_OF_WEEK",
        "DECIMAL_SEPARATOR",
        "THOUSAND_SEPARATOR",
        "NUMBER_GROUPING",
        "DATE_INPUT_FORMATS",
        "TIME_INPUT_FORMATS",
        "DATETIME_INPUT_FORMATS",
    )
    result = {}
    for module in [settings] + get_format_modules(reverse=True):
        for attr in FORMAT_SETTINGS:
            result[attr] = get_format(attr)
    src = []
    for k, v in result.items():
        if isinstance(v, (six.string_types, int)):
            src.append("formats['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(smart_text(v))))
        elif isinstance(v, (tuple, list)):
            v = [javascript_quote(smart_text(value)) for value in v]
            src.append("formats['%s'] = ['%s'];\n" % (javascript_quote(k), "', '".join(v)))
    return "".join(src)
예제 #3
0
파일: i18n.py 프로젝트: ChrisEdson/Inquire
def get_formats():
    """
    Returns all formats strings required for i18n to work
    """
    FORMAT_SETTINGS = (
        'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
        'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
        'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
        'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
        'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
    )
    result = {}
    for module in [settings] + get_format_modules(reverse=True):
        for attr in FORMAT_SETTINGS:
            try:
                result[attr] = getattr(module, attr)
            except AttributeError:
                pass
    src = []
    for k, v in result.items():
        if isinstance(v, (basestring, int)):
            src.append("formats['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(smart_unicode(v))))
        elif isinstance(v, (tuple, list)):
            v = [javascript_quote(smart_unicode(value)) for value in v]
            src.append("formats['%s'] = ['%s'];\n" % (javascript_quote(k), "', '".join(v)))
    return ''.join(src)
예제 #4
0
 def test_deprecation(self):
     reset_warning_registry()
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         text.javascript_quote('thingy')
         self.assertEqual(len(w), 1)
         self.assertIn('escapejs()', repr(w[0].message))
예제 #5
0
def get_formats():
    """
    Returns all formats strings required for i18n to work
    """
    FORMAT_SETTINGS = ('DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
                       'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT',
                       'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT',
                       'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
                       'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
                       'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS',
                       'DATETIME_INPUT_FORMATS')
    result = {}
    for module in [settings] + get_format_modules(reverse=True):
        for attr in FORMAT_SETTINGS:
            result[attr] = get_format(attr)
    src = []
    for k, v in result.items():
        if isinstance(v, (six.string_types, int)):
            src.append("formats['%s'] = '%s';\n" %
                       (javascript_quote(k), javascript_quote(smart_text(v))))
        elif isinstance(v, (tuple, list)):
            v = [javascript_quote(smart_text(value)) for value in v]
            src.append("formats['%s'] = ['%s'];\n" %
                       (javascript_quote(k), "', '".join(v)))
    return ''.join(src)
예제 #6
0
    def test_javascript_quote(self):
        input = "<script>alert('Hello \\xff.\n Welcome\there\r');</script>"
        output = r"<script>alert(\'Hello \\xff.\n Welcome\there\r\');<\/script>"
        self.assertEqual(text.javascript_quote(input), output)

        # Exercising quote_double_quotes keyword argument
        input = '"Text"'
        self.assertEqual(text.javascript_quote(input), '"Text"')
        self.assertEqual(text.javascript_quote(input, quote_double_quotes=True),
                         '&quot;Text&quot;')
예제 #7
0
    def test_javascript_quote(self):
        input = "<script>alert('Hello \\xff.\n Welcome\there\r');</script>"
        output = r"<script>alert(\'Hello \\xff.\n Welcome\there\r\');<\/script>"
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RemovedInDjango19Warning)
            self.assertEqual(text.javascript_quote(input), output)

            # Exercising quote_double_quotes keyword argument
            input = '"Text"'
            self.assertEqual(text.javascript_quote(input), '"Text"')
            self.assertEqual(text.javascript_quote(input, quote_double_quotes=True),
                             '&quot;Text&quot;')
예제 #8
0
    def test_javascript_quote(self):
        input = "<script>alert('Hello \\xff.\n Welcome\there\r');</script>"
        output = r"<script>alert(\'Hello \\xff.\n Welcome\there\r\');<\/script>"
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RemovedInDjango19Warning)
            self.assertEqual(text.javascript_quote(input), output)

            # Exercising quote_double_quotes keyword argument
            input = '"Text"'
            self.assertEqual(text.javascript_quote(input), '"Text"')
            self.assertEqual(text.javascript_quote(input, quote_double_quotes=True),
                             '&quot;Text&quot;')
예제 #9
0
 def testI18NWithLocalePaths(self):
     settings.LANGUAGE_CODE = 'es-ar'
     self.old_locale_paths = settings.LOCALE_PATHS
     settings.LOCALE_PATHS += (path.join(path.dirname(path.dirname(path.abspath(__file__))), 'app3', 'locale'),)
     response = self.client.get('/views/jsi18n/')
     self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
     settings.LOCALE_PATHS = self.old_locale_paths
예제 #10
0
 def testI18NWithLocalePaths(self):
     extended_locale_paths = settings.LOCALE_PATHS + (
         path.join(path.dirname(path.dirname(path.abspath(upath(__file__)))), "app3", "locale"),
     )
     with self.settings(LANGUAGE_CODE="es-ar", LOCALE_PATHS=extended_locale_paths):
         with override("es-ar"):
             response = self.client.get("/views/jsi18n/")
             self.assertContains(response, javascript_quote("este texto de app3 debe ser traducido"))
예제 #11
0
 def testI18NDifferentNonEnLangs(self):
     """
     Similar to above but with neither default or requested language being
     English.
     """
     with self.settings(LANGUAGE_CODE='fr'), override('es-ar'):
         response = self.client.get('/views/jsi18n_multi_packages2/')
         self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
예제 #12
0
 def testI18NWithLocalePaths(self):
     extended_locale_paths = settings.LOCALE_PATHS + (
         path.join(path.dirname(
             path.dirname(path.abspath(upath(__file__)))), 'app3', 'locale'),)
     with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
         with override('es-ar'):
             response = self.client.get('/views/jsi18n/')
             self.assertContains(response,
                 javascript_quote('este texto de app3 debe ser traducido'))
예제 #13
0
파일: i18n.py 프로젝트: 101studio/django
 def testI18NWithLocalePaths(self):
     extended_locale_paths = settings.LOCALE_PATHS + (
         path.join(path.dirname(
             path.dirname(path.abspath(__file__))), 'app3', 'locale'),)
     with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
         with override('es-ar'):
             response = self.client.get('/views/jsi18n/')
             self.assertContains(response,
                 javascript_quote('este texto de app3 debe ser traducido'))
예제 #14
0
 def test_nonenglish_default_english_userpref(self):
     """
     Same as above with the difference that there IS an 'en' translation
     available. The Javascript i18n view must return a NON empty language catalog
     with the proper English translations. See #13726 for more details.
     """
     with self.settings(LANGUAGE_CODE='fr'), override('en-us'):
         response = self.client.get('/views/jsi18n_english_translation/')
         self.assertContains(response, javascript_quote('this app0 string is to be translated'))
예제 #15
0
 def testI18NDifferentNonEnLangs(self):
     """
     Similar to above but with neither default or requested language being
     English.
     """
     with self.settings(LANGUAGE_CODE='fr'), override('es-ar'):
         response = self.client.get('/jsi18n_multi_packages2/')
         self.assertContains(
             response,
             javascript_quote('este texto de app3 debe ser traducido'))
예제 #16
0
 def testI18NDifferentNonEnLangs(self):
     """
     Similar to above but with neither default or requested language being
     English.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ['view_tests.app3', 'view_tests.app4']
     with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
         with override('es-ar'):
             response = self.client.get('/views/jsi18n_multi_packages2/')
             self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
예제 #17
0
파일: i18n.py 프로젝트: 101studio/django
 def testI18NDifferentNonEnLangs(self):
     """
     Similar to above but with neither default or requested language being
     English.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app3', 'regressiontests.views.app4']
     with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
         with override('es-ar'):
             response = self.client.get('/views/jsi18n_multi_packages2/')
             self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
예제 #18
0
 def testI18NDifferentNonEnLangs(self):
     """
     Similar to above but with neither default or requested language being
     English.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ["view_tests.app3", "view_tests.app4"]
     with self.settings(LANGUAGE_CODE="fr", INSTALLED_APPS=extended_apps):
         with override("es-ar"):
             response = self.client.get("/views/jsi18n_multi_packages2/")
             self.assertContains(response, javascript_quote("este texto de app3 debe ser traducido"))
예제 #19
0
 def test_jsi18n(self):
     """The javascript_catalog can be deployed with language settings"""
     for lang_code in ['es', 'fr', 'ru']:
         activate(lang_code)
         catalog = gettext.translation('djangojs', locale_dir, [lang_code])
         trans_txt = catalog.ugettext('this is to be translated')
         response = self.client.get('/views/jsi18n/')
         # in response content must to be a line like that:
         # catalog['this is to be translated'] = 'same_that_trans_txt'
         # javascript_quote is used to be able to check unicode strings
         self.assertContains(response, javascript_quote(trans_txt), 1)
예제 #20
0
 def test_nonenglish_default_english_userpref(self):
     """
     Same as above with the difference that there IS an 'en' translation
     available. The Javascript i18n view must return a NON empty language catalog
     with the proper English translations. See #13726 for more details.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ["view_tests.app0"]
     with self.settings(LANGUAGE_CODE="fr", INSTALLED_APPS=extended_apps):
         with override("en-us"):
             response = self.client.get("/views/jsi18n_english_translation/")
             self.assertContains(response, javascript_quote("this app0 string is to be translated"))
예제 #21
0
 def test_nonenglish_default_english_userpref(self):
     """
     Same as above with the difference that there IS an 'en' translation
     available. The Javascript i18n view must return a NON empty language catalog
     with the proper English translations. See #13726 for more details.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ['view_tests.app0']
     with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
         with override('en-us'):
             response = self.client.get('/views/jsi18n_english_translation/')
             self.assertContains(response, javascript_quote('this app0 string is to be translated'))
예제 #22
0
 def test_jsi18n(self):
     """The javascript_catalog can be deployed with language settings"""
     for lang_code in ["es", "fr", "ru"]:
         activate(lang_code)
         catalog = gettext.translation("djangojs", locale_dir, [lang_code])
         trans_txt = catalog.ugettext("this is to be translated")
         response = self.client.get("/views/jsi18n/")
         # in response content must to be a line like that:
         # catalog['this is to be translated'] = 'same_that_trans_txt'
         # javascript_quote is used to be able to check unicode strings
         self.assertContains(response, javascript_quote(trans_txt), 1)
예제 #23
0
 def testI18NLanguageEnglishDefault(self):
     """
     Check if the JavaScript i18n view returns a complete language catalog
     if the default language is en-us, the selected language has a
     translation available and a catalog composed by djangojs domain
     translations of multiple Python packages is requested. See #13388,
     #3594 and #13514 for more details.
     """
     with self.settings(LANGUAGE_CODE='en-us'), override('fr'):
         response = self.client.get('/views/jsi18n_multi_packages1/')
         self.assertContains(response, javascript_quote('il faut traduire cette chaîne de caractères de app1'))
예제 #24
0
 def testI18NDifferentNonEnLangs(self):
     """
     Similar to above but with neither default or requested language being
     English.
     """
     settings.LANGUAGE_CODE = 'fr'
     settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.views.app3', 'regressiontests.views.app4']
     activate('es-ar')
     response = self.client.get('/views/jsi18n_multi_packages2/')
     self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
     deactivate()
예제 #25
0
 def testI18NLanguageEnglishDefault(self):
     """
     Check if the JavaScript i18n view returns a complete language catalog
     if the default language is en-us, the selected language has a
     translation available and a catalog composed by djangojs domain
     translations of multiple Python packages is requested. See #13388,
     #3594 and #13514 for more details.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ["view_tests.app1", "view_tests.app2"]
     with self.settings(LANGUAGE_CODE="en-us", INSTALLED_APPS=extended_apps):
         with override("fr"):
             response = self.client.get("/views/jsi18n_multi_packages1/")
             self.assertContains(response, javascript_quote("il faut traduire cette chaîne de caractères de app1"))
예제 #26
0
 def testI18NLanguageEnglishDefault(self):
     """
     Check if the JavaScript i18n view returns a complete language catalog
     if the default language is en-us, the selected language has a
     translation available and a catalog composed by djangojs domain
     translations of multiple Python packages is requested. See #13388,
     #3594 and #13514 for more details.
     """
     extended_apps = list(settings.INSTALLED_APPS) + ['view_tests.app1', 'view_tests.app2']
     with self.settings(LANGUAGE_CODE='en-us', INSTALLED_APPS=extended_apps):
         with override('fr'):
             response = self.client.get('/views/jsi18n_multi_packages1/')
             self.assertContains(response, javascript_quote('il faut traduire cette chaîne de caractères de app1'))
예제 #27
0
    def make_js_catalog(self, t):
        items, pitems = [], []
        pdict = {}

        for k, v in t.items():
            if k == '':
                continue
            if isinstance(k, six.string_types):
                items.append("    catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
            elif isinstance(k, tuple):
                if k[0] not in pdict:
                    pdict[k[0]] = k[1]
                else:
                    pdict[k[0]] = max(k[1], pdict[k[0]])
                items.append("    catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
            else:
                raise TypeError(k)
        items.sort()

        for k, v in pdict.items():
            pitems.append("    catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))

        return "".join(items), "".join(pitems)
예제 #28
0
파일: i18n.py 프로젝트: 101studio/django
 def test_jsi18n(self):
     """The javascript_catalog can be deployed with language settings"""
     for lang_code in ['es', 'fr', 'ru']:
         activate(lang_code)
         catalog = gettext.translation('djangojs', locale_dir, [lang_code])
         trans_txt = catalog.ugettext('this is to be translated')
         response = self.client.get('/views/jsi18n/')
         # in response content must to be a line like that:
         # catalog['this is to be translated'] = 'same_that_trans_txt'
         # javascript_quote is used to be able to check unicode strings
         self.assertContains(response, javascript_quote(trans_txt), 1)
         if lang_code == 'fr':
             # Message with context (msgctxt)
             self.assertContains(response, "['month name\x04May'] = 'mai';", 1)
예제 #29
0
파일: i18n.py 프로젝트: zishan74750/django
 def test_jsi18n(self):
     """The javascript_catalog can be deployed with language settings"""
     for lang_code in ['es', 'fr', 'ru']:
         with override(lang_code):
             catalog = gettext.translation('djangojs', locale_dir, [lang_code])
             if six.PY3:
                 trans_txt = catalog.gettext('this is to be translated')
             else:
                 trans_txt = catalog.ugettext('this is to be translated')
             response = self.client.get('/views/jsi18n/')
             # in response content must to be a line like that:
             # catalog['this is to be translated'] = 'same_that_trans_txt'
             # javascript_quote is used to be able to check unicode strings
             self.assertContains(response, javascript_quote(trans_txt), 1)
             if lang_code == 'fr':
                 # Message with context (msgctxt)
                 self.assertContains(response, "['month name\x04May'] = 'mai';", 1)
예제 #30
0
파일: i18n.py 프로젝트: revolunet/django
 def test_jsi18n(self):
     """The javascript_catalog can be deployed with language settings"""
     for lang_code in ["es", "fr", "ru"]:
         with override(lang_code):
             catalog = gettext.translation("djangojs", locale_dir, [lang_code])
             if six.PY3:
                 trans_txt = catalog.gettext("this is to be translated")
             else:
                 trans_txt = catalog.ugettext("this is to be translated")
             response = self.client.get("/views/jsi18n/")
             # in response content must to be a line like that:
             # catalog['this is to be translated'] = 'same_that_trans_txt'
             # javascript_quote is used to be able to check unicode strings
             self.assertContains(response, javascript_quote(trans_txt), 1)
             if lang_code == "fr":
                 # Message with context (msgctxt)
                 self.assertContains(response, "['month name\x04May'] = 'mai';", 1)
예제 #31
0
 def test_jsi18n(self):
     """The javascript_catalog can be deployed with language settings"""
     for lang_code in ['es', 'fr', 'ru']:
         with override(lang_code):
             catalog = gettext.translation('djangojs', locale_dir, [lang_code])
             if six.PY3:
                 trans_txt = catalog.gettext('this is to be translated')
             else:
                 trans_txt = catalog.ugettext('this is to be translated')
             response = self.client.get('/views/jsi18n/')
             # response content must include a line like:
             # "this is to be translated": <value of trans_txt Python variable>
             # javascript_quote is used to be able to check unicode strings
             self.assertContains(response, javascript_quote(trans_txt), 1)
             if lang_code == 'fr':
                 # Message with context (msgctxt)
                 self.assertContains(response, r'"month name\u0004May": "mai"', 1)
예제 #32
0
def get_formats():
    FORMAT_SETTINGS = (
        'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
        'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
        'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
        'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
        'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
    )
    result = {}
    return_result = {}
    for module in [settings] + get_format_modules(reverse=True):
        for attr in FORMAT_SETTINGS:
            result[attr] = get_format(attr)
    for k, v in result.items():
        if isinstance(v, (basestring, int)):
            return_result[k] = smart_unicode(v)
        elif isinstance(v, (tuple, list)):
            v = [javascript_quote(smart_unicode(value)) for value in v]
            return_result[k] = "', '".join(v)
    return return_result
예제 #33
0
 def test_javascript_quote_unicode(self):
     input = "<script>alert('Hello \\xff.\n Wel𝕃come\there\r');</script>"
     output = r"<script>alert(\'Hello \\xff.\n Wel𝕃come\there\r\');<\/script>"
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", RemovedInDjango19Warning)
         self.assertEqual(text.javascript_quote(input), output)
예제 #34
0
 def javascript_quoted_title(self):
     return mark_safe(u"'%s'" % javascript_quote(self.title))
예제 #35
0
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if request.GET.has_key('language'):
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if type(packages) in (str, unicode):
        packages = packages.split('+')
    packages = [
        p for p in packages
        if p == 'django.conf' or p in settings.INSTALLED_APPS
    ]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    # first load all english languages files for defaults
    for package in packages:
        p = __import__(package, {}, {}, [''])
        path = os.path.join(os.path.dirname(p.__file__), 'locale')
        paths.append(path)
        catalog = gettext_module.translation(domain, path, ['en'])
        t.update(catalog._catalog)
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path,
                                                     [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    src = [LibHead]
    plural = None
    if t.has_key(''):
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':', 1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [
            el.strip() for el in plural.split(';')
            if el.strip().startswith('plural=')
        ][0].split('=', 1)[1]
        src.append('function pluralidx(n) {\n    return %s;\n}\n' % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if type(k) in (str, unicode):
            csrc.append("catalog['%s'] = '%s';\n" %
                        (javascript_quote(k), javascript_quote(v)))
        elif type(k) == tuple:
            if not pdict.has_key(k[0]):
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" %
                        (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError, k
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" %
                   (javascript_quote(k), ','.join(["''"] * (v + 1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')
예제 #36
0
파일: i18n.py 프로젝트: ChrisEdson/Inquire
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if 'language' in request.GET:
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, basestring):
        packages = packages.split('+')
    packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    en_catalog_missing = False
    # first load all english languages files for defaults
    for package in packages:
        p = importlib.import_module(package)
        path = os.path.join(os.path.dirname(p.__file__), 'locale')
        paths.append(path)
        try:
            catalog = gettext_module.translation(domain, path, ['en'])
            t.update(catalog._catalog)
        except IOError:
            # 'en' catalog was missing.
            if locale.startswith('en'):
                # If 'en' is the selected language this would cause issues
                # later on if default_locale is something other than 'en'.
                en_catalog_missing = True
            # Otherwise it is harmless.
            pass
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        # If the flag en_catalog_missing has been set, the currently
        # selected language is English but it doesn't have a translation
        # catalog (presumably due to being the language translated from).
        # If that is the case, a wrong language catalog might have been
        # loaded in the previous step. It needs to be discarded.
        if en_catalog_missing:
            t = {}
        else:
            locale_t = {}
            for path in paths:
                try:
                    catalog = gettext_module.translation(domain, path, [locale])
                except IOError:
                    catalog = None
                if catalog is not None:
                    locale_t.update(catalog._catalog)
            if locale_t:
                t = locale_t
    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':',1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if isinstance(k, basestring):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif isinstance(k, tuple):
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError(k)
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src.append(LibFormatHead)
    src.append(get_formats())
    src.append(LibFormatFoot)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')
예제 #37
0
def javascript_catalog(locale, domain, packages):
    packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    t = {}
    paths = []
    en_selected = locale.startswith('en')
    en_catalog_missing = True
    # paths of requested packages
    for package in packages:
        p = importlib.import_module(package)
        path = os.path.join(os.path.dirname(p.__file__), 'locale')
        paths.append(path)
    # add the filesystem paths listed in the LOCALE_PATHS setting
    paths.extend(list(reversed(settings.LOCALE_PATHS)))
    # first load all english languages files for defaults
    for path in paths:
        try:
            catalog = gettext_module.translation(domain, path, ['en'])
            t.update(catalog._catalog)
        except IOError:
            pass
        else:
            # 'en' is the selected language and at least one of the packages
            # listed in `packages` has an 'en' catalog
            if en_selected:
                en_catalog_missing = False
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        # If the currently selected language is English but it doesn't have a
        # translation catalog (presumably due to being the language translated
        # from) then a wrong language catalog might have been loaded in the
        # previous step. It needs to be discarded.
        if en_selected and en_catalog_missing:
            t = {}
        else:
            locale_t = {}
            for path in paths:
                try:
                    catalog = gettext_module.translation(domain, path, [locale])
                except IOError:
                    catalog = None
                if catalog is not None:
                    locale_t.update(catalog._catalog)
            if locale_t:
                t = locale_t
    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':', 1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if isinstance(k, basestring):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif isinstance(k, tuple):
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError(k)
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"] * (v + 1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src.append(LibFormatHead)
    src.append(get_formats())
    src.append(LibFormatFoot)
    src = ''.join(src)
    return src
예제 #38
0
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    # (TODO): cache dictionary
    if request.GET:
        if 'language' in request.GET:
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')
    packages = [p for p in packages if p ==
                'django.conf' or p in settings.INSTALLED_APPS]
    locale = to_locale(get_language())
    t = {}

    # Singular forms
    aux_catalog = Message.objects.filter(
        domain=domain, plural__isnull=True, language=locale).values_list(
        "msgid", "msgstr", "translation")

    for message in aux_catalog:
        # Case there is translation
        if len(message[2]):
            aux_message = {message[0]: message[2]}
        # Case no translation but .po msgstr translation
        elif len(message[1]):
            aux_message = {message[0]: message[1]}
        # Case no translations
        else:
            aux_message = {message[0]: message[0]}

        t.update(aux_message)

    # Plural forms (TODO)
    # plural_msgs = dict(Message.objects.filter(
    #     domain=domain, plural__isnull=False).values_list(
    #     "msgid", "translation"))

    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':', 1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2
        # && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(
            ';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}

    for k, v in t.items():
        if k == '':
            continue
        if isinstance(k, six.string_types):
            if len(v) == 0:
                csrc.append("catalog['%s'] = '%s';\n" %
                            (javascript_quote(k), javascript_quote(k)))
            else:
                csrc.append("catalog['%s'] = '%s';\n" %
                            (javascript_quote(k), javascript_quote(v)))
        elif isinstance(k, tuple):
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (
                javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError(k)
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" %
                   (javascript_quote(k), ','.join(["''"] * (v + 1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src.append(LibFormatHead)
    src.append(get_formats())
    src.append(LibFormatFoot)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')
예제 #39
0
 def test_javascript_quote_unicode(self):
     input = "<script>alert('Hello \\xff.\n Wel𝕃come\there\r');</script>"
     output = r"<script>alert(\'Hello \\xff.\n Wel𝕃come\there\r\');<\/script>"
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", RemovedInDjango19Warning)
         self.assertEqual(text.javascript_quote(input), output)
예제 #40
0
 def render_tag(self, context, **kwargs):
     rendered = self.nodelist.render(context)
     return u"'%s'" % javascript_quote(rendered.strip())
예제 #41
0
파일: i18n.py 프로젝트: 0xmilk/appscale
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if request.GET.has_key('language'):
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if type(packages) in (str, unicode):
        packages = packages.split('+')
    packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    # first load all english languages files for defaults
    for package in packages:
        p = __import__(package, {}, {}, [''])
        path = os.path.join(os.path.dirname(p.__file__), 'locale')
        paths.append(path)
        catalog = gettext_module.translation(domain, path, ['en'])
        t.update(catalog._catalog)
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    src = [LibHead]
    plural = None
    if t.has_key(''):
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':',1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
        src.append('function pluralidx(n) {\n    return %s;\n}\n' % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if type(k) in (str, unicode):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif type(k) == tuple:
            if not pdict.has_key(k[0]):
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError, k
    csrc.sort()
    for k,v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')
예제 #42
0
 def render_tag(self, context, **kwargs):
     rendered = self.nodelist.render(context)
     return u"'%s'" % javascript_quote(rendered.strip())
예제 #43
0
 def test_javascript_quote_unicode(self):
     input = "<script>alert('Hello \\xff.\n Wel𝕃come\there\r');</script>"
     output = r"<script>alert(\'Hello \\xff.\n Wel𝕃come\there\r\');<\/script>"
     self.assertEqual(text.javascript_quote(input), output)
예제 #44
0
 def javascript_quoted_title(self):
     return mark_safe(u"'%s'" % javascript_quote(self.title))
예제 #45
0
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if 'language' in request.GET:
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if type(packages) in (str, unicode):
        packages = packages.split('+')
    packages = [
        p for p in packages
        if p == 'django.conf' or p in settings.INSTALLED_APPS
    ]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    en_catalog_missing = False
    # first load all english languages files for defaults
    for package in packages:
        p = importlib.import_module(package)
        path = os.path.join(os.path.dirname(p.__file__), 'locale')
        paths.append(path)
        try:
            catalog = gettext_module.translation(domain, path, ['en'])
            t.update(catalog._catalog)
        except IOError:
            # 'en' catalog was missing.
            if locale.startswith('en'):
                # If 'en' is the selected language this would cause issues
                # later on if default_locale is something other than 'en'.
                en_catalog_missing = True
            # Otherwise it is harmless.
            pass
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path,
                                                     [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        # If the flag en_catalog_missing has been set, the currently
        # selected language is English but it doesn't have a translation
        # catalog (presumably due to being the language translated from).
        # If that is the case, a wrong language catalog might have been
        # loaded in the previous step. It needs to be discarded.
        if en_catalog_missing:
            t = {}
        else:
            locale_t = {}
            for path in paths:
                try:
                    catalog = gettext_module.translation(
                        domain, path, [locale])
                except IOError:
                    catalog = None
                if catalog is not None:
                    locale_t.update(catalog._catalog)
            if locale_t:
                t = locale_t
    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':', 1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [
            el.strip() for el in plural.split(';')
            if el.strip().startswith('plural=')
        ][0].split('=', 1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if type(k) in (str, unicode):
            csrc.append("catalog['%s'] = '%s';\n" %
                        (javascript_quote(k), javascript_quote(v)))
        elif type(k) == tuple:
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" %
                        (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError, k
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" %
                   (javascript_quote(k), ','.join(["''"] * (v + 1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')
예제 #46
0
파일: i18n.py 프로젝트: RaoUmer/django
def javascript_catalog(request, domain="djangojs", packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if "language" in request.GET:
            if check_for_language(request.GET["language"]):
                activate(request.GET["language"])
    if packages is None:
        packages = ["django.conf"]
    if isinstance(packages, six.string_types):
        packages = packages.split("+")
    packages = [p for p in packages if p == "django.conf" or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    en_selected = locale.startswith("en")
    en_catalog_missing = True
    # paths of requested packages
    for package in packages:
        p = importlib.import_module(package)
        path = os.path.join(os.path.dirname(p.__file__), "locale")
        paths.append(path)
    # add the filesystem paths listed in the LOCALE_PATHS setting
    paths.extend(list(reversed(settings.LOCALE_PATHS)))
    # first load all english languages files for defaults
    for path in paths:
        try:
            catalog = gettext_module.translation(domain, path, ["en"])
            t.update(catalog._catalog)
        except IOError:
            pass
        else:
            # 'en' is the selected language and at least one of the packages
            # listed in `packages` has an 'en' catalog
            if en_selected:
                en_catalog_missing = False
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != "en":
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        # If the currently selected language is English but it doesn't have a
        # translation catalog (presumably due to being the language translated
        # from) then a wrong language catalog might have been loaded in the
        # previous step. It needs to be discarded.
        if en_selected and en_catalog_missing:
            t = {}
        else:
            locale_t = {}
            for path in paths:
                try:
                    catalog = gettext_module.translation(domain, path, [locale])
                except IOError:
                    catalog = None
                if catalog is not None:
                    locale_t.update(catalog._catalog)
            if locale_t:
                t = locale_t
    src = [LibHead]
    plural = None
    if "" in t:
        for l in t[""].split("\n"):
            if l.startswith("Plural-Forms:"):
                plural = l.split(":", 1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(";") if el.strip().startswith("plural=")][0].split("=", 1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == "":
            continue
        if isinstance(k, six.string_types):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif isinstance(k, tuple):
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError(k)
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ",".join(["''"] * (v + 1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src.append(LibFormatHead)
    src.append(get_formats())
    src.append(LibFormatFoot)
    src = "".join(src)
    return http.HttpResponse(src, "text/javascript")