本文整理汇总了Python中pylons.i18n.get_lang函数的典型用法代码示例。如果您正苦于以下问题:Python get_lang函数的具体用法?Python get_lang怎么用?Python get_lang使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_lang函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: default
def default(self, obj):
model = model_instance()
if isinstance(obj, model.AuthenticatedUser):
return {"uid": obj.uid, "username": obj.username, "email": obj.email}
if isinstance(obj, model.Balance):
return {
"uid": obj.uid,
"name": obj.name,
"users": [{"user_uid": user.user_uid, "writable": user.writable} for user in obj.users],
}
if isinstance(obj, model.BalanceChange):
return {
"uid": obj.uid,
"amount": obj.amount,
"category_uid": obj.is_income and obj.income_category_uid or obj.expense_category_uid,
"description": obj.description,
"tags": obj.tags_as_string(),
}
if isinstance(obj, Decimal):
return babel.numbers.format_decimal(obj, locale=get_lang()[0]).replace(
babel.numbers.get_group_symbol(locale=get_lang()[0]), " "
)
if isinstance(obj, date) or isinstance(obj, datetime):
return str(obj)
return simplejson.JSONEncoder.default(self, obj)
示例2: handle_request
def handle_request(request, tmpl_context):
from pylons import session
tmpl_context.language = locale = None
if 'locale' in session:
locale = Locale.parse(session.get('locale'))
else:
requested = [l.replace('-', '_') for l in request.languages]
locale = Locale.parse(Locale.negotiate(get_available_languages(), requested))
if locale is None:
locale = get_default_locale()
tmpl_context.locale = locale
options = [str(locale), locale.language, str(get_default_locale()),
get_default_locale().language]
for language in options:
try:
set_lang(language)
# Lose the territory part of the locale string
tmpl_context.language = get_lang()[0].split('_')[0]
break
except:
pass
示例3: get_translator
def get_translator(lang=None):
"""
return a GNUTranslations instance for `lang`::
>>> translator = get_translator('fr')
... assert translator.gettext('Remove') == 'Supprimer'
... assert translator.gettext('month_01') == 'Janvier'
>>> translator = get_translator('en')
... assert translator.gettext('Remove') == 'Remove'
... assert translator.gettext('month_01') == 'January'
"""
# get possible fallback languages
try:
langs = get_lang() or []
except TypeError:
# this occurs when Pylons is available and we are not in a valid thread
langs = []
# insert lang if provided
if lang and lang not in langs:
langs.insert(0, lang)
if not langs:
langs = ['en']
# get the first available catalog
for lang in langs:
filename = os.path.join(i18n_path, lang, 'LC_MESSAGES','formalchemy.mo')
if os.path.isfile(filename):
translations_path = os.path.join(i18n_path, lang, 'LC_MESSAGES','formalchemy.mo')
return GNUTranslations(open(translations_path, 'rb'))
# dummy translator
return _Translator()
示例4: _save_new
def _save_new(self, context, group_type=None):
try:
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
data_dict['type'] = group_type or 'group'
context['message'] = data_dict.get('log_message', '')
data_dict['users'] = [{'name': c.user, 'capacity': 'admin'}]
group = self._action('group_create')(context, data_dict)
log.info('::::: Persisting localised metadata locale :::::')
lang = get_lang()[0]
session = model.Session
try:
session.add_all([
GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='title', lang=lang, text=group.get('title')),
GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='description', lang=lang, text=group.get('description')),
])
session.commit()
except Exception, e:
# on rollback, the same closure of state
# as that of commit proceeds.
session.rollback()
log.error('Exception occurred while persisting DB objects: %s', e)
raise
# Redirect to the appropriate _read route for the type of group
h.redirect_to(group['type'] + '_read', id=group['name'])
示例5: _save_edit
def _save_edit(self, id, context):
try:
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
context['message'] = data_dict.get('log_message', '')
data_dict['id'] = id
context['allow_partial_update'] = True
group = self._action('group_update')(context, data_dict)
if id != group['name']:
self._force_reindex(group)
log.info(':::::::::::: Saving the corresponding localized title and abstract :::::::::::::::')
lang = get_lang()[0]
q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == group.get('id')).all()
create_new = False
if q_results:
available_db_lang = []
for result in q_results:
if result.lang not in available_db_lang:
available_db_lang.append(result.lang)
# check if the group identifier name has been changed
if result.name != group.get('name'):
result.name = group.get('name')
result.save()
if lang not in available_db_lang:
create_new = True
else:
for result in q_results:
if result.lang == lang:
result.text = group.get(result.field)
result.save()
else:
create_new = True
if create_new == True:
log.info(':::::::::::: Localized fields are missing in package_multilang table, persisting defaults using values in the table group :::::::::::::::')
session = model.Session
try:
session.add_all([
GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='title', lang=lang, text=group.get('title')),
GroupMultilang(group_id=group.get('id'), name=group.get('name'), field='description', lang=lang, text=group.get('description')),
])
session.commit()
except Exception, e:
# on rollback, the same closure of state
# as that of commit proceeds.
session.rollback()
log.error('Exception occurred while persisting DB objects: %s', e)
raise
h.redirect_to('%s_read' % group['type'], id=group['name'])
示例6: get_lang
def get_lang():
''' Returns the current language. Based on babel.i18n.get_lang but
works when set_lang has not been run (i.e. still in English). '''
langs = i18n.get_lang()
if langs:
return langs[0]
else:
return 'hr'
示例7: login
def login(self):
"""
This is where the login form should be rendered.
Without the login counter, we won't be able to tell if the user has
tried to log in with wrong credentials
"""
came_from = request.params.get('came_from', None)
identity = request.environ.get('repoze.who.identity')
if identity:
return render(path.join(get_lang()[0],'derived/account/login.mako'))
else:
c.login_counter = request.environ['repoze.who.logins'] + 1
if came_from:
session['came_from'] = came_from
session.save()
return render(path.join(get_lang()[0],'derived/account/logindialog.mako'))
return render(path.join(get_lang()[0],'derived/account/login.mako'))
示例8: use
def use(self):
from pylons.i18n import get_lang
from r2.lib.template_helpers import static
embed = Module.use(self)
if g.uncompressedJS:
return embed + StringsSource().use()
else:
url = LocalizedModule.languagize_path(self.name, get_lang()[0])
return script_tag.format(src=static(url))
示例9: render_customer_form
def render_customer_form(
menu_items, id, values=None, action=None, errors=None, add_number_of_addresses=0, add_number_of_phones=0
):
c.number_of_addresses = number_of_addresses(values) + add_number_of_addresses
c.number_of_phones = number_of_phones(values) + add_number_of_phones
c.menu_items = h.top_menu(menu_items, _("Customers"))
c.id = id
html = render(path.join(get_lang()[0], "derived/user/customer/edit.mako"))
return htmlfill.render(html, defaults=values, errors=errors)
示例10: use
def use(self):
from pylons.i18n import get_lang
from r2.lib.template_helpers import static
embed = Module.use(self)
if g.uncompressedJS:
return embed + StringsSource().use()
else:
name, ext = os.path.splitext(self.name)
url = os.path.join(g.static_path, name + "." + get_lang()[0] + ext)
return script_tag.format(src=static(url))
示例11: get_lang
def get_lang():
''' Returns the current language. Based on babel.i18n.get_lang but
works when set_lang has not been run (i.e. still in English). '''
if is_flask_request():
from ckan.config.middleware.flask_app import get_locale
return get_locale()
else:
langs = i18n.get_lang()
if langs:
return langs[0]
return 'en'
示例12: _month_details
def _month_details(cls, stat_key=None):
'''
Returns a list of all the periods for which we have data and the date we've
got data up to in the latest month.
e.g. ([(u'2014-11', 'November 2014'),
(u'2014-10', 'October 2014'),
(u'2014-09', 'September 2014')],
'27th')
i.e. we have 3 months up to 27th November
:param cls: GA_Stat or GA_Url
unfortunately
knows too much about the type of the cls being passed as GA_Url has a
more complex query
This may need extending if we add a period_name to the stats
'''
months = []
day = None
q = model.Session.query(cls.period_name, cls.period_complete_day)\
.filter(cls.period_name!='All') \
.distinct(cls.period_name)
if stat_key:
q = q.filter(cls.stat_name==stat_key)
vals = q.order_by("period_name desc").all()
lang = get_lang()
#log.debug(lang)
# If lang is None the actual language is english,
# if lang is 'es' the actual language is spanish
# otherwise the month is rendered in english language.
if lang and lang[0] == 'es':
# For the most recent month in spanish
if vals and vals[0][1]:
day = int(vals[0][1])
else:
# For the most recent month, add 'ordinal' to the day
# e.g. '27' -> day='27th'
if vals and vals[0][1]:
day = int(vals[0][1])
ordinal = 'th' if 11 <= day <= 13 \
else {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th')
day = "{day}{ordinal}".format(day=day, ordinal=ordinal)
for m in vals:
months.append((m[0], _get_month_name(m[0])))
return months, day
示例13: i18n
def i18n(self):
import gettext
import pylons
import os.path
# Repris de pylons.i18n.translation:_get_translator.
conf = pylons.config.current_conf()
try:
rootdir = conf['pylons.paths']['root']
except KeyError:
rootdir = conf['pylons.paths'].get('root_path')
localedir = os.path.join(rootdir, 'i18n')
lang = get_lang()
# Localise le fichier *.mo actuellement chargé
# et génère le chemin jusqu'au *.js correspondant.
filename = gettext.find(conf['pylons.package'], localedir,
languages=lang)
js = filename[:-3] + '.js'
# Récupère et envoie le contenu du fichier de traduction *.js.
fhandle = open(js, 'r')
translations = fhandle.read()
fhandle.close()
# Même chose pour les thèmes
themes_filename = gettext.find(
'vigilo-themes',
resource_filename('vigilo.themes.i18n', ''),
languages=lang)
themes_js = themes_filename[:-3] + '.js'
fhandle = open(themes_js, 'r')
translations += fhandle.read()
fhandle.close()
# Extensions Enterprise
try:
ent_filename = gettext.find(
'vigilo-vigigraph-enterprise',
resource_filename('vigilo.vigigraph_enterprise.i18n', ''),
languages=lang)
except ImportError:
pass
else:
# Le nom du fichier sera None s'il n'existe pas
# de traductions dans la langue demandée.
if ent_filename is not None:
fhandle = open(ent_filename[:-3] + '.js', 'r')
translations += fhandle.read()
fhandle.close()
return translations
示例14: fallback_trans
def fallback_trans(x):
"""For translating placeholder strings the user should never see
in raw form, such as 'funny 500 message'. If the string does not
translate in the current language, falls back on the g.lang
translation that we've hopefully already provided"""
t = _(x)
if t == x:
l = get_lang()
set_lang(g.lang, graceful_fail = True)
t = _(x)
if l and l[0] != g.lang:
set_lang(l[0])
return t
示例15: document
def document(self):
"""Render the error document"""
request = self._py_object.request
resp = request.environ.get('pylons.original_response')
code = cgi.escape(request.GET.get('code', ''))
content = cgi.escape(request.GET.get('message', ''))
c.menu_items = h.top_menu(self.menu_items,_('Home'))
if resp:
content = literal(resp.status)
code = code or cgi.escape(str(resp.status_int))
if not code:
raise Exception("No Status code was found")
c.code = code
c.message = content
return render(path.join(get_lang()[0],'derived/error/error.mako'))