/usr/lib/python2.7/dist-packages/tg/i18n.py is in python-turbogears2 2.3.7-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | import copy
import logging, os
import gettext as _gettext
from gettext import NullTranslations, GNUTranslations
import warnings
import tg
from tg.util import lazify
from tg._compat import PY3, string_type
log = logging.getLogger(__name__)
class LanguageError(Exception):
"""Exception raised when a problem occurs with changing languages"""
pass
def _parse_locale(identifier, sep='_'):
"""
Took from Babel,
Parse a locale identifier into a tuple of the form::
``(language, territory, script, variant)``
>>> parse_locale('zh_CN')
('zh', 'CN', None, None)
>>> parse_locale('zh_Hans_CN')
('zh', 'CN', 'Hans', None)
The default component separator is "_", but a different separator can be
specified using the `sep` parameter:
:see: `IETF RFC 4646 <http://www.ietf.org/rfc/rfc4646.txt>`_
"""
if '.' in identifier:
# this is probably the charset/encoding, which we don't care about
identifier = identifier.split('.', 1)[0]
if '@' in identifier:
# this is a locale modifier such as @euro, which we don't care about
# either
identifier = identifier.split('@', 1)[0]
parts = identifier.split(sep)
lang = parts.pop(0).lower()
if not lang.isalpha():
raise ValueError('expected only letters, got %r' % lang)
script = territory = variant = None
if parts:
if len(parts[0]) == 4 and parts[0].isalpha():
script = parts.pop(0).title()
if parts:
if len(parts[0]) == 2 and parts[0].isalpha():
territory = parts.pop(0).upper()
elif len(parts[0]) == 3 and parts[0].isdigit():
territory = parts.pop(0)
if parts:
if len(parts[0]) == 4 and parts[0][0].isdigit() or\
len(parts[0]) >= 5 and parts[0][0].isalpha():
variant = parts.pop()
if parts:
raise ValueError('%r is not a valid locale identifier' % identifier)
return lang, territory, script, variant
def gettext_noop(value):
"""Mark a string for translation without translating it. Returns
value.
"""
return value
def ugettext(value):
"""Mark a string for translation. Returns the localized unicode
string of value.
Mark a string to be localized as follows::
_('This should be in lots of languages')
"""
if PY3: #pragma: no cover
return tg.translator.gettext(value)
else:
return tg.translator.ugettext(value)
lazy_ugettext = lazify(ugettext)
def ungettext(singular, plural, n):
"""Mark a string for translation. Returns the localized unicode
string of the pluralized value.
This does a plural-forms lookup of a message id. ``singular`` is
used as the message id for purposes of lookup in the catalog, while
``n`` is used to determine which plural form to use. The returned
message is a Unicode string.
Mark a string to be localized as follows::
ungettext('There is %(num)d file here', 'There are %(num)d files here',
n) % {'num': n}
"""
if PY3: #pragma: no cover
return tg.translator.ngettext(singular, plural, n)
else:
return tg.translator.ungettext(singular, plural, n)
lazy_ungettext = lazify(ungettext)
_TRANSLATORS_CACHE = {}
def _translator_from_mofiles(domain, mofiles, class_=None, fallback=False):
"""
Adapted from python translation function in gettext module
to work with a provided list of mo files
"""
if class_ is None:
class_ = GNUTranslations
if not mofiles:
if fallback:
return NullTranslations()
raise LanguageError('No translation file found for domain %s' % domain)
result = None
for mofile in mofiles:
key = (class_, os.path.abspath(mofile))
t = _TRANSLATORS_CACHE.get(key)
if t is None:
with open(mofile, 'rb') as fp:
# Cache Translator to avoid reading it again
t = _TRANSLATORS_CACHE.setdefault(key, class_(fp))
t = copy.copy(t)
if result is None:
# Copy the translation object to be able to append fallbacks
# without affecting the cached object.
result = t
else:
result.add_fallback(t)
return result
def _get_translator(lang, tgl=None, tg_config=None, **kwargs):
"""Utility method to get a valid translator object from a language name"""
if tg_config:
conf = tg_config
else:
if tgl:
conf = tgl.config
else: # pragma: no cover
#backward compatibility with explicit calls without
#specifying local context or config.
conf = tg.config.current_conf()
if not lang:
return NullTranslations()
try:
localedir = conf['localedir']
except KeyError: # pragma: no cover
localedir = os.path.join(conf['paths']['root'], 'i18n')
app_domain = conf['package'].__name__
if not isinstance(lang, list):
lang = [lang]
mofiles = []
supported_languages = []
for l in lang:
mo = _gettext.find(app_domain, localedir=localedir, languages=[l], all=False)
if mo is not None:
mofiles.append(mo)
supported_languages.append(l)
try:
translator = _translator_from_mofiles(app_domain, mofiles, **kwargs)
except IOError as ioe:
raise LanguageError('IOError: %s' % ioe)
translator.tg_lang = lang
translator.tg_supported_lang = supported_languages
return translator
def get_lang(all=True):
"""
Return the current i18n languages used
returns ``None`` if no supported language is available (no translations
are in place) or a list of languages.
In case ``all`` parameter is ``False`` only the languages for which
the application is providing a translation are returned. Otherwise
all the languages preferred by the user are returned.
"""
if all is False:
return getattr(tg.translator, 'tg_supported_lang', [])
return getattr(tg.translator, 'tg_lang', [])
def add_fallback(lang, **kwargs):
"""Add a fallback language from which words not matched in other
languages will be translated to.
This fallback will be associated with the currently selected
language -- that is, resetting the language via set_lang() resets
the current fallbacks.
This function can be called multiple times to add multiple
fallbacks.
"""
tgl = tg.request_local.context._current_obj()
return tg.translator.add_fallback(_get_translator(lang, tgl=tgl, **kwargs))
sanitized_language_cache = {}
def sanitize_language_code(lang):
"""Sanitize the language code if the spelling is slightly wrong.
For instance, 'pt-br' and 'pt_br' should be interpreted as 'pt_BR'.
"""
try:
lang = sanitized_language_cache[lang]
except:
orig_lang = lang
try:
lang = '_'.join(filter(None, _parse_locale(lang)[:2]))
except ValueError:
if '-' in lang:
try:
lang = '_'.join(filter(None, _parse_locale(lang, sep='-')[:2]))
except ValueError:
pass
sanitized_language_cache[orig_lang] = lang
return lang
def set_request_lang(languages, tgl=None):
"""Set the current request language(s) used for translations
without touching the session language.
languages should be a string or a list of strings.
First lang will be used as main lang, others as fallbacks.
"""
# the logging to the screen was removed because
# the printing to the screen for every problem causes serious slow down.
if not tgl:
tgl = tg.request_local.context._current_obj()
# Should only raise exceptions in case of IO errors,
# so we let them propagate to the developer.
tgl.translator = _get_translator(languages, tgl=tgl, fallback=True)
# If the application has a set of supported translation
# limit the formencode translations to those so that
# we don't get the application in a language and
# the errors in another one
supported_languages = get_lang(all=False)
if supported_languages:
languages = supported_languages
try:
set_formencode_translation(languages, tgl=tgl)
except LanguageError:
pass
def set_temporary_lang(*args, **kwargs):
warnings.warn("i18n.set_temporary_lang has been deprecated in favor of"
"i18n.set_request_lang and will be removed.", DeprecationWarning)
return set_request_lang(*args, **kwargs)
def set_lang(languages, **kwargs):
"""Set the current language(s) used for translations
in current call and session.
languages should be a string or a list of strings.
First lang will be used as main lang, others as fallbacks.
"""
tgl = tg.request_local.context._current_obj()
set_request_lang(languages, tgl)
if tgl.session:
tgl.session[tgl.config.get('lang_session_key', 'tg_lang')] = languages
tgl.session.save()
FormEncodeMissing = '_MISSING_FORMENCODE'
formencode = None
_localdir = None
def set_formencode_translation(languages, tgl=None):
"""Set request specific translation of FormEncode."""
global formencode, _localdir
if formencode is FormEncodeMissing: # pragma: no cover
return
if formencode is None:
try:
import formencode
_localdir = formencode.api.get_localedir()
except ImportError: # pragma: no cover
formencode = FormEncodeMissing
return
if not tgl: # pragma: no cover
tgl = tg.request_local.context._current_obj()
try:
formencode_translation = _gettext.translation('FormEncode',
languages=languages,
localedir=_localdir)
except IOError as error:
raise LanguageError('IOError: %s' % error)
tgl.translator._formencode_translation = formencode_translation
# Idea stolen from Pylons
def _formencode_gettext(value):
trans = ugettext(value)
# Translation failed, try formencode
if trans == value:
try:
fetrans = tg.translator._formencode_translation
except (AttributeError, TypeError):
# the translator was not set in the TG context
# we are certainly in the test framework
# let's make sure won't return something that is ok with the caller
fetrans = None
if not fetrans:
fetrans = NullTranslations()
translator_gettext = getattr(fetrans, 'ugettext', fetrans.gettext)
trans = translator_gettext(value)
return trans
__all__ = [
"set_lang", "get_lang", "add_fallback",
"set_request_lang", "set_temporary_lang",
"ugettext", "lazy_ugettext", "ungettext", "lazy_ungettext"
]
|