本文整理汇总了Python中pyramid.i18n.make_localizer函数的典型用法代码示例。如果您正苦于以下问题:Python make_localizer函数的具体用法?Python make_localizer怎么用?Python make_localizer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了make_localizer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_localizer
def set_localizer(request, reset=False):
'''
Sets localizer and auto_translate methods for request
:param pyramid.request.Request request: request object
:param bool reset: flag that directs resetting localizer within app
'''
if reset:
for locale in request.config.localize.locales.available:
logger.debug('Resetting {0} localizator'.format(locale))
tdirs = request.registry.queryUtility(ITranslationDirectories,
default=[])
localizer = make_localizer(locale, tdirs)
request.registry.registerUtility(localizer, ILocalizer,
name=locale)
def auto_translate(*args, **kwargs):
# lets pass default domain, so we don't have to determine it with
# each _() function in apps.
if len(args) <= 1 and not 'domain' in kwargs:
kwargs['domain'] = request.config.localize.domain
# unlike in examples we use TranslationString, to make sure we always
# use appropriate domain
return request.localizer.translate(TranslationString(*args, **kwargs))
request._ = auto_translate
示例2: test_known_indexes_no_matches
def test_known_indexes_no_matches(self):
localizer = make_localizer(
current_locale_name='fre_FR',
translation_directories=['springboard_iogt/locale'])
self.assert_sections_equal(
ContentSection.known_indexes(['win', 'rar'], localizer),
[])
示例3: get_localizer
def get_localizer(cls, user=None):
if user:
locale = user.get_preferred_locale()
else:
locale = config.get(
'available_languages', 'fr_CA en_CA').split()[0]
# TODO: if locale has country code, make sure we fallback properly.
path = os.path.abspath(join(dirname(__file__), os.path.pardir, 'locale'))
return make_localizer(locale, [path])
示例4: test_known_indexes_multiple_matches
def test_known_indexes_multiple_matches(self):
localizer = make_localizer(
current_locale_name='fre_FR',
translation_directories=['springboard_iogt/locale'])
self.assert_sections_equal(
ContentSection.known_indexes(['fflazer', 'fflafel'], localizer),
[ContentSection('ffl', localizer, 'fflazer'),
ContentSection('ffl', localizer, 'fflafel')])
示例5: test_content_section_translations
def test_content_section_translations(self):
localizer = make_localizer(
current_locale_name='fre_FR',
translation_directories=['springboard_iogt/locale']
)
sections = ContentSection.known(indexes=['ffl'], localizer=localizer)
section_obj = sections[0]
self.assertEqual(section_obj.slug, 'ffl')
self.assertEqual(section_obj.title, 'Savoir pour Sauver')
示例6: test_content_section_translation
def test_content_section_translation(self):
localizer = make_localizer(
current_locale_name='fre_FR',
translation_directories=['springboard_iogt/locale']
)
[page] = self.mk_pages(self.workspace, count=1)
section_obj = filters.content_section(page, localizer)
self.assertIs(section_obj, None)
page.es_meta = Mock(index='unicore-cms-content-ffl-za-qa')
section_obj = filters.content_section(page, localizer)
self.assertEqual(section_obj.slug, 'ffl')
self.assertEqual(section_obj.title, 'Savoir pour Sauver')
示例7: translate
def translate(string, country):
# hack to use en locale for us country
if country == 'us':
country = 'en'
if country in localizers:
localizer = localizers[country]
else:
here = os.path.dirname(__file__)
local_path = os.path.join(here, '../locale')
localizer = make_localizer(country, [local_path])
localizers[country] = localizer
return localizer.translate(trans(string))
示例8: get_custom_localizer
def get_custom_localizer(locale):
if locale == None:
locale = Config.get_string_value('pyramid.default_locale_name')
registry = Config.registry
localizer = registry.queryUtility(ILocalizer, name=locale)
if localizer is None:
# no localizer utility registered yet
tdirs = registry.queryUtility(ITranslationDirectories, default=[])
localizer = make_localizer(locale, tdirs)
registry.registerUtility(localizer, ILocalizer,
name=locale)
return localizer
示例9: sys_localizer
def sys_localizer(reg):
cur_locale = reg.settings.get('pyramid.default_locale_name', 'en')
sys_locale = locale.getlocale()[0]
if sys_locale:
new_locale = Locale.negotiate(
(sys_locale,),
reg.settings.get('pyramid.available_languages', '').split())
if new_locale:
cur_locale = str(new_locale)
else:
cur_locale = 'en'
tdirs = reg.queryUtility(ITranslationDirectories, default=[])
return make_localizer(cur_locale, tdirs)
示例10: _add_fts
def _add_fts(self, item, interface, action, role):
key = (
item.name if self.options.name else item.id,
interface.id,
role.id if role is not None else None
)
if key not in self.imported:
self.imported.add(key)
for lang in self.languages:
localizer = make_localizer(lang, self.tdirs)
translated_name = localizer.translate(self.tsf(item.name))
if role is None:
role_id = None
else:
role_id = role.id
fts = {
'layer_id': item.id,
'name_translated': translated_name,
'name': item.name,
'role_id': role_id,
'interface': interface.name,
'language': lang,
'public': role is None,
'type': action,
'keywords': '',
'description': '',
'metadata_name': ''
}
for metadata in item.ui_metadata:
if metadata.name == 'metadata_id':
params = dict(
uid=metadata.value,
lang=lang
)
try:
resp = requests.get(url=self.metadata_service_url,
params=params)
data = json.loads(resp.text)
fts['keywords'] = data['root'][0]['keywords']
fts['description'] = \
data['root'][0]['description']
fts['metadata_name'] = data['root'][0]['name']
except requests.exceptions.RequestException as e:
statuslog("\n %s" % e)
sys.exit(1)
doc = self._update_document(fts)
self.layers.append(doc)
示例11: create_localized_langstring
def create_localized_langstring(
cls, trans_string, desired_locales=None, known_translations=None):
"""Construct a langstring from a localized string.
Call with a TranslationString."""
inst = cls.create(trans_string, 'en')
known_translations = known_translations or {}
for loc in desired_locales or ():
if loc == 'en':
continue
elif loc in known_translations:
inst.add_value(known_translations[loc], loc)
else:
from pyramid.i18n import make_localizer
from os.path import dirname, join
loc_dir = join(dirname(dirname(__file__)), 'locale')
localizer = make_localizer(loc, loc_dir)
inst.add_value(localizer.translate(trans_string), loc)
return inst
示例12: get_localizer
def get_localizer(self):
locale = self.first_matching_subscription.user.get_preferred_locale()
if not locale:
locale = self.first_matching_subscription.discussion.get_discussion_locales()[0]
return make_localizer(locale, [
join(dirname(dirname(__file__)), 'locale')])
示例13: getInputFiles
def getInputFiles(output_type, export_dir_path, save_dir_path='', translation_dirs=[]):
"""
Return a list of path to index.html and chapter.html files if it's a collection.
Return turn the path to index.html only if it's a module.
Collection file structrure looks like:
collection-x/
collection.json
module-1/
index.html
p1.jpg
p2.jpg
...
module-2/
index.html
p1.jpg
p2.jpg
...
"""
results = []
err_msg = None
# FIXED config filename
config_filename = 'collection.json'
config_filepath = os.path.join(export_dir_path, config_filename)
try:
with open(config_filepath, 'rb') as cf:
lines = cf.readlines()
data = ''.join([line.strip('\n').strip() for line in lines])
try:
collection = json.loads(data)
except ValueError, e:
err_msg = 'ValueError [parsing collection.json]: %s' % e.message
return results, err_msg
# processing the title page
title = collection['title']
editors = collection.get('editors')
language = collection.get('language', 'vi')
# making localizer for i18n translation
localizer = make_localizer(language, translation_dirs)
title_filepath = os.path.join(export_dir_path, 'title.html')
createTitlePage(title_filepath, title, editors, save_dir_path=save_dir_path, localizer=localizer)
# add path of title.html into result list
results.append(title_filepath)
# recursively process collection content
data = processCollection(export_dir_path, collection['content'], save_dir_path=save_dir_path, localizer=localizer)
authors = data[2]
# processing the title page 2
title_filepath2 = os.path.join(export_dir_path, 'title2.html')
createTitlePage(title_filepath2, title, editors, authors, collection.get('url'),
collection.get('version'), save_dir_path=save_dir_path, localizer=localizer)
# add path of title2.html into result list
results.append(title_filepath2)
tocs = data[1]
tocs.sort(key=lambda toc: toc[2])
# create a toc.html file
toc_filename = 'toc.html'
toc_filepath = os.path.join(export_dir_path, toc_filename)
createTOCPage(toc_filepath, tocs, localizer=localizer)
results.append(toc_filepath)
# add path of modules index.html into result list
results.extend(data[0])
# processing contribution page
contrib_filename = 'contrib.html'
contrib_filepath = os.path.join(export_dir_path, contrib_filename)
createContributionPage(contrib_filepath, collection, data[3], localizer=localizer)
results.append(contrib_filepath)
# add end page
endfile_name = 'end_%s.html' % language
endfile_path = os.path.join(save_dir_path, endfile_name)
results.append(endfile_path)
if output_type == 'epub':
# epub export only need toc file
return [toc_filepath, ], err_msg
except IOError:
# it's a module
metadata_filepath = os.path.join(export_dir_path, 'metadata.json')
with open(metadata_filepath, 'rb') as mf:
lines = mf.readlines()
json_data = ''.join([line.strip('\n').strip() for line in lines])
try:
metadata = json.loads(json_data)
except ValueError, e:
err_msg = 'ValueError [parsing metadata.json]: %s' % e.message
return results, err_msg
language = metadata.get('language', 'vi')
# making localizer for i18n translation
localizer = make_localizer(language, translation_dirs)
data = processModule(export_dir_path, localizer=localizer)
results.extend(data[0])
err_msg = data[1]
示例14: get_localizer
def get_localizer(self):
locale = self.first_matching_subscription.user.get_preferred_locale()
# TODO: if locale has country code, make sure we fallback properly.
path = os.path.abspath(join(dirname(__file__), os.path.pardir, 'locale'))
return make_localizer(locale, [path])
示例15: get_localizer_for_locale_name
def get_localizer_for_locale_name(locale_name):
registry = get_current_registry()
tdirs = registry.queryUtility(ITranslationDirectories, default=[])
return make_localizer(locale_name, tdirs)