• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python i18n.get_lang函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pylons.i18n.get_lang函数的典型用法代码示例。如果您正苦于以下问题:Python get_lang函数的具体用法?Python get_lang怎么用?Python get_lang使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_lang函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:pawelniewie,项目名称:5groszy.pl,代码行数:29,代码来源:decorators.py


示例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
开发者ID:RandyMoore,项目名称:openspending,代码行数:25,代码来源:__init__.py


示例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()
开发者ID:Alwnikrotikz,项目名称:formalchemy,代码行数:35,代码来源:i18n.py


示例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'])
开发者ID:geosolutions-it,项目名称:ckanext-multilang,代码行数:30,代码来源:group.py


示例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'])
开发者ID:geosolutions-it,项目名称:ckanext-multilang,代码行数:59,代码来源:group.py


示例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'
开发者ID:tbalaz,项目名称:test,代码行数:8,代码来源:i18n.py


示例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'))
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:17,代码来源:account.py


示例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))
开发者ID:LDot,项目名称:reddit,代码行数:9,代码来源:js.py


示例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)
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:9,代码来源:user.py


示例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))
开发者ID:DeanHyde,项目名称:reddit,代码行数:10,代码来源:js.py


示例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'
开发者ID:CIOIL,项目名称:DataGovIL,代码行数:11,代码来源:i18n.py


示例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
开发者ID:SENATICS,项目名称:ckanext-ga-report,代码行数:52,代码来源:controller.py


示例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
开发者ID:vigilo,项目名称:vigigraph,代码行数:52,代码来源:root.py


示例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
开发者ID:bodegard,项目名称:reddit,代码行数:13,代码来源:strings.py


示例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'))
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:15,代码来源:error.py


示例16: index

    def index(self, category="Main", page=1):
        c.lang = get_lang() 
        c.sites = []
        if not category:
            c.error = _("Sorry, there is no such category.")
            return redirect(url(controller="category", action="index"))

        c.category = CategoryModel.get_by_slug(category)
        c.site_name = str('name_'+c.lang[0])
        c.site_descr = str('description_'+c.lang[0])
        if c.category.id is None:
            c.error = _("Sorry, there is no such category.")
            c.category = CategoryModel.get_by_slug("Main")

        if int(c.category.is_leaf) == 1:
            c.sites = SiteModel.get_by_category(int(c.category.id),page,lang=c.lang)
            c.totals = CategoryModel().get_totals({'category_id':int(c.category.id)})
            c.pages = c.totals/20 + 1  if (c.totals/20) else c.totals/20
        c.cur_page = page
        c.slug = c.category.slug
        children = c.category.get_children()[1:]
        
        c.children = []
        for child in children:
            if re.search(u'[a-zA-Zа-яА-я]+', child[0].to_dict['title_'+c.lang[0]]):
                child[0].title = child[0].to_dict['title_'+c.lang[0]]
            if len(child)>0:
                for i in range(1,len(child)):
                    if re.search(u'[a-zA-Zа-яА-я]+', child[i][0].to_dict['title_'+c.lang[0]]):
                        child[i][0].title = child[i][0].to_dict['title_'+c.lang[0]]

            c.children.append(child)

        c.keywords = c.category.to_dict.get('keywords')
        c.description = c.category.to_dict.get('description')

        if re.search(u'[a-zA-Zа-яА-я]', c.category.to_dict['title_'+c.lang[0]]):
            c.category.title = c.category.to_dict['title_'+c.lang[0]]

        breadcrunchs = []
        if int(c.category.id) != 0:
            breadcrunchs =  CategoryModel.get_path(c.category)
        c.breadcrunchs = []
        for crunch in breadcrunchs:
            if re.search(u'[a-zA-Zа-яА-я]+', crunch.to_dict.get('title_'+c.lang[0],'')):
                crunch.title = crunch.to_dict['title_'+c.lang[0]]
            c.breadcrunchs.append(crunch)
        return render('/category/category.mako.html')
开发者ID:testTemtProj,项目名称:OLD_PROJECT,代码行数:48,代码来源:category.py


示例17: index

    def index(self):
        group_type = self._guess_group_type()

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'for_view': True,
                   'with_private': False}

        q = c.q = request.params.get('q', '')
        data_dict = {'all_fields': True, 'q': q, 'type': group_type or 'group'}
        sort_by = c.sort_by_selected = request.params.get('sort')
        if sort_by:
            data_dict['sort'] = sort_by
        try:
            self._check_access('site_read', context)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

        # pass user info to context as needed to view private datasets of
        # orgs correctly
        if c.userobj:
            context['user_id'] = c.userobj.id
            context['user_is_admin'] = c.userobj.sysadmin

        results = self._action('group_list')(context, data_dict)

        c.page = h.Page(
            collection=results,
            page = self._get_page_number(request.params),
            url=h.pager_url,
            items_per_page=21
        )

        log.info(':::::::::::: Retrieving the corresponding localized title and abstract :::::::::::::::')
        for item in c.page.items:   
            lang = get_lang()[0]
            
            q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == item.get('id'), GroupMultilang.lang == lang).all() 

            if q_results:
                for result in q_results:
                    item[result.field] = result.text
                    if result.field == 'title':
                        item['display_name'] = result.text


        return render(self._index_template(group_type),
                      extra_vars={'group_type': group_type})
开发者ID:geosolutions-it,项目名称:ckanext-multilang,代码行数:47,代码来源:group.py


示例18: edit

    def edit(self, id, data=None, errors=None, error_summary=None):
        group_type = self._ensure_controller_matches_group_type(
            id.split('@')[0])

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'save': 'save' in request.params,
                   'for_edit': True,
                   'parent': request.params.get('parent', None)
                   }
        data_dict = {'id': id, 'include_datasets': False}

        if context['save'] and not data:
            return self._save_edit(id, context)

        try:
            data_dict['include_datasets'] = False
            old_data = self._action('group_show')(context, data_dict)
            c.grouptitle = old_data.get('title')
            c.groupname = old_data.get('name')
            data = data or old_data
        except NotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read group %s') % '')

        group = context.get("group")
        c.group = group
        c.group_dict = self._action('group_show')(context, data_dict)

        log.info(':::::::::::: Retrieving the corresponding localized title and abstract :::::::::::::::')

        lang = get_lang()[0]

        q_results = model.Session.query(GroupMultilang).filter(GroupMultilang.group_id == data.get('id'), GroupMultilang.lang == lang).all()

        if q_results:
            for result in q_results:
                data[result.field] = result.text
                c.group_dict[result.field] = result.text
                if result.field == 'title':
                    c.group_dict['display_name'] = result.text

        try:
            self._check_access('group_update', context)
        except NotAuthorized, e:
            abort(401, _('User %r not authorized to edit %s') % (c.user, id))
开发者ID:geosolutions-it,项目名称:ckanext-multilang,代码行数:47,代码来源:group.py


示例19: search

 def search(self):
     identity = request.environ.get("repoze.who.identity")
     c.menu_items = h.top_menu(self.menu_items, _("Customers"))
     c.tags = Session.query(UserTag.tag).all()
     action = request.params.getone("action")
     values = dict(request.params)
     del values["action"]
     schema = UserSearch()
     try:
         result = schema.to_python(values)
     except Invalid, e:
         html = render(path.join(get_lang()[0], "/derived/user/staff/index.html"))
         return htmlfill.render(
             html,
             defaults=values,
             errors=variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False),
         )
开发者ID:vickyi,项目名称:PylonsSimpleCMS,代码行数:17,代码来源:user.py


示例20: use

    def use(self):
        from pylons.i18n import get_lang
        from r2.lib.template_helpers import static

        if g.uncompressedJS:
            if c.lang == "en":
                # in this case, the msgids *are* the translated strings and we
                # can save ourselves the pricey step of lexing the js source
                return Module.use(self)

            msgids = extract_javascript_msgids(Module.get_source(self))
            strings = StringsSource(c.lang, msgids)
            return "\n".join(
                (Module.use(self), inline_script_tag.format(content=strings.get_plural_forms()), strings.use())
            )
        else:
            langs = get_lang() or [g.lang]
            url = LocalizedModule.languagize_path(self.name, langs[0])
            return script_tag.format(src=static(url))
开发者ID:songv,项目名称:reddit,代码行数:19,代码来源:js.py



注:本文中的pylons.i18n.get_lang函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python i18n.gettext函数代码示例发布时间:2022-05-25
下一篇:
Python i18n._函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap