def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found (generally Django's).
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog)
python类NullTranslations()的实例源码
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active.value = gettext_module.NullTranslations()
_active.value.to_language = lambda *args: None
def get_translation_for(self, locale, domain):
translation = self.translations.get((locale, domain), None)
if not translation:
with self.map_lock:
for package in ReahlSystemConfig().translation_packages:
for locale_dir in package.__path__:
if not isinstance(translation, Translations):
translation = Translations.load(dirname=locale_dir, locales=[locale], domain=domain)
# Babel 1.3 bug under Python 3: files is a filter object, not a list like in Python 2
translation.files = list(translation.files)
else:
translation.merge(Translations.load(dirname=locale_dir, locales=[locale], domain=domain))
self.translations[(locale, domain)] = translation
return translation or gettext.NullTranslations()
def get_plugin_instance(plugin_class, *extra_args):
info = type('', (object,),
{
'name': 'pluginunittest',
'translations':
{'en-US': gettext.NullTranslations()}})()
args = tuple(extra_args) + (info, TEST_PROFILE)
return plugin_class(*args)
def parse_translations(translations_path):
translations = {}
if os.path.isdir(translations_path):
for content in os.listdir(translations_path):
if not os.path.isdir(os.path.join(translations_path, content)):
lang, ext = os.path.splitext(content)
if ext == (os.extsep + 'mo') and RE_TRANSLATIONS.match(lang):
with open(os.path.join(translations_path, content),
mode="rb") as f:
translations[lang] = gettext.GNUTranslations(f)
if not translations:
# Untranslated module, assume hardcoded en-US strings
translations['en-US'] = gettext.NullTranslations()
return translations
def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found (generally Django's).
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog)
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active.value = gettext_module.NullTranslations()
_active.value.to_language = lambda *args: None
def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found (generally Django's).
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog)
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active.value = gettext_module.NullTranslations()
_active.value.to_language = lambda *args: None
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active[currentThread()] = gettext_module.NullTranslations()
def app(postgres, mocker, caplog):
caplog.set_level(logging.WARNING, logger='ckan.lib.i18n')
caplog.set_level(logging.WARNING, logger='migrate')
caplog.set_level(logging.WARNING, logger='pyutilib')
caplog.set_level(logging.WARNING, logger='vdm')
caplog.set_level(logging.WARNING, logger='pysolr')
global_config = {
'__file__': '',
'here': os.path.dirname(__file__),
'ckan.site_url': 'http://localhost',
'ckan.plugins': 'harvest odgovlt_harvester',
'sqlalchemy.url': postgres,
'ckanext.harvest.user_name': 'harvest',
# 'solr_url': 'http://127.0.0.1:8983/solr/ckan',
}
app_config = {
'who.config_file': pres.resource_filename('ckan.config', 'who.ini'),
'beaker.session.secret': 'secret',
}
app = ckan.config.middleware.make_app(global_config, **app_config)
app = CKANTestApp(app)
ckan.model.repo.init_db()
ckanext.harvest.model.setup()
pylons.translator = gettext.NullTranslations()
return app
def load_translations(self, dirname, locales, domains):
"""Loads a translation catalog.
:param dirname:
Path to where translations are stored.
:param locales:
A list of locale codes.
:param domains:
A list of domains to be merged.
:returns:
A ``babel.support.Translations`` instance, or
``gettext.NullTranslations`` if none was found.
"""
trans = None
trans_null = None
for domain in domains:
_trans = support.Translations.load(dirname, locales, domain)
if isinstance(_trans, NullTranslations):
trans_null = _trans
continue
elif trans is None:
trans = _trans
else:
trans.merge(_trans)
return trans or trans_null or NullTranslations()
def init_localization(): # pragma: no cover
"""
Application localization
:return: gettext translator method
:rtype: method
"""
try:
# Language message file
if 'win32' not in sys.platform:
lang_filename = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
"LC_MESSAGES/%s.mo" % get_app_config('Alignak-app', 'locale')
)
else:
lang_filename = get_main_folder() + "\\locales\\%s.mo" % get_app_config(
'Alignak-app', 'locale'
)
logger.info(
"Opening message file %s for locale %s",
lang_filename, get_app_config('Alignak-app', 'locale')
)
translation = GNUTranslations(open(lang_filename, "rb"))
translation.install()
_ = translation.gettext
except IOError:
logger.warning("Locale not found. Using default language messages (English)")
null_translation = NullTranslations()
null_translation.install()
_ = null_translation.gettext
except Exception as e: # pragma: no cover - should not happen
logger.error("Locale not found. Exception: %s", str(e))
null_translation = NullTranslations()
null_translation.install()
_ = null_translation.gettext
return _
def __init__(self, trans=None):
self.trans = NullTranslations() if trans is None else trans
def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found (generally Django's).
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog)
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active.value = gettext_module.NullTranslations()
_active.value.to_language = lambda *args: None
def i18n_wrapper(locale: Optional[str] = None) -> Any:
"""
Internationalize using gettext.
Returns gettext for provided locale
or default (zentropi.defaults.LOCALE).
Example:
>>> from zentropi.utils import i18n_wrapper
>>> _ = i18n_wrapper()
>>> print(_('Hello, world.'))
Hello, world.
"""
from zentropi import BASE_PATH
from zentropi.defaults import LOCALE
locale = locale or lib_locale.getlocale()[0] or LOCALE
locale_dir = os.path.join(BASE_PATH, 'locale')
locale_file = os.path.join(locale_dir, '{}.mo'.format(locale))
try:
translation = gettext.GNUTranslations(open(locale_file, 'rb'))
except IOError:
warnings.warn('Translation file for {} not found at: {}. Using default.'
''.format(locale, locale_file))
translation = gettext.NullTranslations() # type: ignore
translation.install()
return translation.gettext
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active.value = gettext_module.NullTranslations()
_active.value.to_language = lambda *args: None