Пример #1
0
 def __init__(self, template_string, name="<string>", loader=None,
              compress_whitespace=None, autoescape=_UNSET):
     self.name = name
     if compress_whitespace is None:
         compress_whitespace = name.endswith(".html") or \
             name.endswith(".js")
     if autoescape is not _UNSET:
         self.autoescape = autoescape
     elif loader:
         self.autoescape = loader.autoescape
     else:
         self.autoescape = _DEFAULT_AUTOESCAPE
     self.namespace = loader.namespace if loader else {}
     reader = _TemplateReader(name, escape.native_str(template_string))
     self.file = _File(self, _parse(reader, self))
     self.code = self._generate_python(loader, compress_whitespace)
     self.loader = loader
     try:
         # Under python2.5, the fake filename used here must match
         # the module name used in __name__ below.
         # The dont_inherit flag prevents template.py's future imports
         # from being applied to the generated code.
         self.compiled = compile(
             escape.to_unicode(self.code),
             "%s.generated.py" % self.name.replace('.', '_'),
             "exec", dont_inherit=True)
     except Exception:
         formatted_code = _format_code(self.code).rstrip()
         app_log.error("%s code:\n%s", self.name, formatted_code)
         raise
Пример #2
0
 def handle_read(self, data):
     logging.info("handle_read")
     data = to_unicode(data)
     if data == data.upper():
         self.stream.write(b"error\talready capitalized\n")
     else:
         # data already has \n
         self.stream.write(utf8("ok\t%s" % data.upper()))
     self.stream.close()
Пример #3
0
 def test_url_unescape_unicode(self):
     tests = [
         ('%C3%A9', u('\u00e9'), 'utf8'),
         ('%C3%A9', u('\u00c3\u00a9'), 'latin1'),
         ('%C3%A9', utf8(u('\u00e9')), None),
     ]
     for escaped, unescaped, encoding in tests:
         # input strings to url_unescape should only contain ascii
         # characters, but make sure the function accepts both byte
         # and unicode strings.
         self.assertEqual(url_unescape(to_unicode(escaped), encoding), unescaped)
         self.assertEqual(url_unescape(utf8(escaped), encoding), unescaped)
Пример #4
0
 def test_utf8_in_file(self):
     tmpl = self.loader.load("utf8.html")
     result = tmpl.generate()
     self.assertEqual(to_unicode(result).strip(), u("H\u00e9llo"))
Пример #5
0
 def upper(s):
     return utf8(to_unicode(s).upper())
Пример #6
0
 def upper(s):
     return to_unicode(s).upper()
Пример #7
0
 def process_response(self, data):
     status, message = re.match('(.*)\t(.*)\n', to_unicode(data)).groups()
     if status == 'ok':
         return message
     else:
         raise CapError(message)
Пример #8
0
def load_translations(directory):
    """Loads translations from CSV files in a directory.

    Translations are strings with optional Python-style named placeholders
    (e.g., ``My name is %(name)s``) and their associated translations.

    The directory should have translation files of the form ``LOCALE.csv``,
    e.g. ``es_GT.csv``. The CSV files should have two or three columns: string,
    translation, and an optional plural indicator. Plural indicators should
    be one of "plural" or "singular". A given string can have both singular
    and plural forms. For example ``%(name)s liked this`` may have a
    different verb conjugation depending on whether %(name)s is one
    name or a list of names. There should be two rows in the CSV file for
    that string, one with plural indicator "singular", and one "plural".
    For strings with no verbs that would change on translation, simply
    use "unknown" or the empty string (or don't include the column at all).

    The file is read using the `csv` module in the default "excel" dialect.
    In this format there should not be spaces after the commas.

    Example translation ``es_LA.csv``::

        "I love you","Te amo"
        "%(name)s liked this","A %(name)s les gustó esto","plural"
        "%(name)s liked this","A %(name)s le gustó esto","singular"

    """
    global _translations
    global _supported_locales
    _translations = {}
    for path in os.listdir(directory):
        if not path.endswith(".csv"):
            continue
        locale, extension = path.split(".")
        if not re.match("[a-z]+(_[A-Z]+)?$", locale):
            gen_log.error("Unrecognized locale %r (path: %s)", locale,
                          os.path.join(directory, path))
            continue
        full_path = os.path.join(directory, path)
        try:
            # python 3: csv.reader requires a file open in text mode.
            # Force utf8 to avoid dependence on $LANG environment variable.
            f = open(full_path, "r", encoding="utf-8")
        except TypeError:
            # python 2: files return byte strings, which are decoded below.
            f = open(full_path, "r")
        _translations[locale] = {}
        for i, row in enumerate(csv.reader(f)):
            if not row or len(row) < 2:
                continue
            row = [escape.to_unicode(c).strip() for c in row]
            english, translation = row[:2]
            if len(row) > 2:
                plural = row[2] or "unknown"
            else:
                plural = "unknown"
            if plural not in ("plural", "singular", "unknown"):
                gen_log.error("Unrecognized plural indicator %r in %s line %d",
                              plural, path, i + 1)
                continue
            _translations[locale].setdefault(plural, {})[english] = translation
        f.close()
    _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
    gen_log.debug("Supported locales: %s", sorted(_supported_locales))