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

Python i18n._函数代码示例

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

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



在下文中一共展示了_函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: rightbox

    def rightbox(self):
        """generates content in <div class="rightbox">"""
        
        ps = PaneStack(css_class='spacer')

        if self.searchbox:
            ps.append(SearchForm())

        if not c.user_is_loggedin and self.loginbox:
            ps.append(LoginFormWide())

        #don't show the subreddit info bar on cnames
        if not isinstance(c.site, FakeSubreddit) and not c.cname:
            ps.append(SubredditInfoBar())

        if self.submit_box:
            ps.append(SideBox(_('Submit a link'),
                              '/submit', 'submit',
                              sr_path = True,
                              subtitles = [_('to anything interesting: news article, blog entry, video, picture...')],
                              show_cover = True))
            
        if self.create_reddit_box:
           ps.append(SideBox(_('Create your own reddit'),
                              '/reddits/create', 'create',
                              subtitles = rand_strings.get("create_reddit", 2),
                              show_cover = True, nocname=True))
        return ps
开发者ID:vin,项目名称:reddit,代码行数:28,代码来源:pages.py


示例2: after_login

 def after_login(self):
     if c.account is not None:
         h.flash_success(_("Welcome back, %s!") % c.account.name)
         redirect("/")
     else:
         h.flash_error(_("Incorrect user name or password!"))
         redirect("/login")
开发者ID:asuffield,项目名称:openspending,代码行数:7,代码来源:account.py


示例3: _connect

    def _connect(self, adhocracy_user, domain, domain_user,
                 provider_name,
                 velruse_email, email_verified=False,
                 redirect_url=None):
        """
        Connect existing adhocracy user to velruse.
        """

        if not Velruse.find(domain, domain_user):
            velruse_user = Velruse.connect(adhocracy_user, domain, domain_user,
                                           velruse_email, email_verified)

            model.meta.Session.commit()

            h.flash(_("You successfully connected to %s."
                      % provider_name.capitalize()),
                    'success')

            if redirect_url is None:
                redirect(h.user.post_login_url(adhocracy_user))
            else:
                redirect(redirect_url)
            return velruse_user

        else:
            h.flash(_("Your %s account is already connected."
                      % provider_name.capitalize()),
                    'error')

            redirect(h.user.post_login_url(adhocracy_user))
            return None
开发者ID:alkadis,项目名称:vcv,代码行数:31,代码来源:velruse.py


示例4: history_ajax

    def history_ajax(self, id):

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'extras_as_string': True,}
        data_dict = {'id':id}
        try:
            pkg_revisions = get_action('package_revision_list')(context, data_dict)
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % '')
        except NotFound:
            abort(404, _('Dataset not found'))


        data = []
        approved = False
        for num, revision in enumerate(pkg_revisions):
            if not approved and revision['approved_timestamp']:
                current_approved, approved = True, True
            else:
                current_approved = False
            
            data.append({'revision_id': revision['id'],
                         'message': revision['message'],
                         'timestamp': revision['timestamp'],
                         'author': revision['author'],
                         'approved': bool(revision['approved_timestamp']),
                         'current_approved': current_approved})
                
        response.headers['Content-Type'] = 'application/json;charset=utf-8'
        return json.dumps(data)
开发者ID:icmurray,项目名称:ckan,代码行数:31,代码来源:package.py


示例5: vocabulary_update

def vocabulary_update(context, data_dict):
    model = context['model']

    vocab_id = data_dict.get('id')
    if not vocab_id:
        raise ValidationError({'id': _('id not in data')})

    vocab = model.vocabulary.Vocabulary.get(vocab_id)
    if vocab is None:
        raise NotFound(_('Could not find vocabulary "%s"') % vocab_id)

    data_dict['id'] = vocab.id
    if data_dict.has_key('name'):
        if data_dict['name'] == vocab.name:
            del data_dict['name']

    check_access('vocabulary_update', context, data_dict)

    schema = context.get('schema') or ckan.logic.schema.default_update_vocabulary_schema()
    data, errors = validate(data_dict, schema, context)

    if errors:
        model.Session.rollback()
        raise ValidationError(errors)

    updated_vocab = model_save.vocabulary_dict_update(data, context)

    if not context.get('defer_commit'):
        model.repo.commit()

    return model_dictize.vocabulary_dictize(updated_vocab, context)
开发者ID:slmnhq,项目名称:ckan,代码行数:31,代码来源:update.py


示例6: make_tables

    def make_tables(self):
        # overall promoted link traffic
        impressions = traffic.AdImpressionsByCodename.historical_totals("day")
        clicks = traffic.ClickthroughsByCodename.historical_totals("day")
        data = traffic.zip_timeseries(impressions, clicks)

        columns = [
            dict(color=COLORS.UPVOTE_ORANGE,
                 title=_("total impressions by day"),
                 shortname=_("impressions")),
            dict(color=COLORS.DOWNVOTE_BLUE,
                 title=_("total clicks by day"),
                 shortname=_("clicks")),
        ]

        self.totals = TimeSeriesChart("traffic-ad-totals",
                                      _("ad totals"),
                                      "day",
                                      columns,
                                      data,
                                      self.traffic_last_modified,
                                      classes=["traffic-table"])

        # get summary of top ads
        advert_summary = traffic.AdImpressionsByCodename.top_last_month()
        things = AdvertTrafficSummary.get_things(ad for ad, data
                                                 in advert_summary)
        self.advert_summary = []
        for id, data in advert_summary:
            name = AdvertTrafficSummary.get_ad_name(id, things=things)
            url = AdvertTrafficSummary.get_ad_url(id, things=things)
            self.advert_summary.append(((name, url), data))
开发者ID:AjaxGb,项目名称:reddit,代码行数:32,代码来源:trafficpages.py


示例7: user_name_exists

def user_name_exists(user_name, context):
    model = context['model']
    session = context['session']
    result = session.query(model.User).filter_by(name=user_name).first()
    if not result:
        raise Invalid('%s: %s' % (_('Not found'), _('User')))
    return result.name
开发者ID:code4sac,项目名称:ckan,代码行数:7,代码来源:validators.py


示例8: pretty_name

 def pretty_name(self):
     if self.is_collection:
         return _("collection: %(name)s") % {'name': self.collection.name}
     elif self.subreddit_name == Frontpage.name:
         return _("frontpage")
     else:
         return "/r/%s" % self.subreddit_name
开发者ID:rgandsam,项目名称:reddit,代码行数:7,代码来源:promo.py


示例9: _try_sign_in

    def _try_sign_in(self, username, password, location=None, remember=False):
        # user may have registered in several Ututi
        # networks using same username
        locations = [user.location for user in User.get_all(username)]
        if len(locations) == 0:
            return {'username': _('Incorrect username.')}

        if len(locations) > 1:
            # if there is more than one location,
            # we will want to show it in the form
            c.locations = [(loc.id, loc.title) for loc in locations]
            c.selected_location = location

        if location is None and len(locations) == 1:
            location = locations[0].id

        if location is None:
            # still none! that means that location is not
            # unique and user did not specify it.
            return {'location': _('Please select your network.')}

        user = User.authenticate(location, username, password)
        if user is None:
            return {'password': _('Incorrect password.')}

        sign_in_user(user, long_session=remember)
开发者ID:nous-consulting,项目名称:ututi,代码行数:26,代码来源:home.py


示例10: read

    def read(self, id):
        from ckan.lib.search import SearchError
        group_type = self._get_group_type(id.split('@')[0])
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author,
                   'schema': self._db_to_form_schema(group_type=group_type),
                   'for_view': True, 'extras_as_string': True}
        data_dict = {'id': id}
        # unicode format (decoded from utf8)
        q = c.q = request.params.get('q', '')

        try:
            c.group_dict = get_action('group_show')(context, data_dict)
            c.group = context['group']
        except NotFound:
            abort(404, _('Group not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read group %s') % id)

        # Search within group
        q += ' groups: "%s"' % c.group_dict.get('name')

        try:
            description_formatted = ckan.misc.MarkdownFormat().to_html(
            c.group_dict.get('description', ''))
            c.description_formatted = genshi.HTML(description_formatted)
        except Exception, e:
            error_msg = "<span class='inline-warning'>%s</span>" %\
                        _("Cannot render description")
            c.description_formatted = genshi.HTML(error_msg)
开发者ID:rostock,项目名称:opendata.hro,代码行数:30,代码来源:group.py


示例11: edit

    def edit(self, id, data=None, errors=None, error_summary=None):
        group_type = self._get_group_type(id.split('@')[0])
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'extras_as_string': True,
                   'save': 'save' in request.params,
                   'for_edit': True,
                   'parent': request.params.get('parent', None)
                   }
        data_dict = {'id': id}

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

        try:
            old_data = get_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

        try:
            check_access('group_update', context)
        except NotAuthorized, e:
            abort(401, _('User %r not authorized to edit %s') % (c.user, id))
开发者ID:rostock,项目名称:opendata.hro,代码行数:30,代码来源:group.py


示例12: nuevo

    def nuevo(self, id_fase, **kw):
        """Despliega el formulario para añadir una linea base a la fase"""
	fase=DBSession.query(Fase).get(id_fase)
	#Comprobación de si el estado de la fase se encuentra en Con Lineas Bases
	if fase.relacion_estado_fase.nombre_estado=='Con Lineas Bases':
		flash(_("Todos los items de esta fase ya se encuentran en una Linea Base Aprobada"), 'warning')
                redirect("/admin/linea_base/listado_linea_bases",id_proyecto=fase.id_proyecto, id_fase=id_fase)	    
	tipo_items=DBSession.query(TipoItem).filter_by(id_fase=id_fase)
	itemsDeFaseActual = []
	for tipo_item in tipo_items:
		itemsTipoItem = DBSession.query(Item).filter_by(id_tipo_item=tipo_item.id_tipo_item).filter_by(vivo=True)
		for itemTipoItem in itemsTipoItem:
			itemsDeFaseActual.append(itemTipoItem)
	contador_items_en_fase_actual = 0
	for item in itemsDeFaseActual:
		contador_items_en_fase_actual = contador_items_en_fase_actual + 1
	#Comprobación de si existen items cargados para la fase actual
	if contador_items_en_fase_actual == 0:
		flash(_("Aun no existen items cargados para esta fase"), 'warning')
                redirect("/admin/linea_base/listado_linea_bases",id_proyecto=fase.id_proyecto, id_fase=id_fase)		
        kw['id_estado']= 'Desarrollo'
        kw['id_fase']= id_fase
	kw['version']= '1'
	tmpl_context.form = crear_linea_base_form
        return dict(nombre_modelo='LineaBase', id_proyecto=fase.id_proyecto, id_fase=id_fase, page='nuevo', value=kw)
开发者ID:albertgarcpy,项目名称:IS2SAP,代码行数:25,代码来源:linea_base_controlador.py


示例13: edit

    def edit(self, id, data = None,errors = None, error_summary = None):

        if ('save' in request.params) and not data:
            return self._save_edit(id)

        try:
            context = {'model':model, 'user':c.user, 'include_status':False}

            old_data = p.toolkit.get_action('harvest_source_show')(context, {'id':id})
        except p.toolkit.ObjectNotFound:
            abort(404, _('Harvest Source not found'))
        except p.toolkit.NotAuthorized:
            abort(401, self.not_auth_message)
        try:
            p.toolkit.check_access('harvest_source_update', context)
        except p.toolkit.NotAuthorized:
            abort(401, _('Unauthorized to update the harvest source'))

        data = data or old_data
        errors = errors or {}
        error_summary = error_summary or {}
        try:
            context = {'model': model, 'user': c.user}
            harvesters_info = p.toolkit.get_action('harvesters_info_show')(context, {})
        except p.toolkit.NotAuthorized:
            abort(401, self.not_auth_message)

        vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'harvesters': harvesters_info}

        c.source_title = old_data.get('title') if old_data else ''
        c.source_id = id
        c.groups = self._get_publishers()
        c.form = render('source/new_source_form.html', extra_vars=vars)
        return render('source/edit.html')
开发者ID:tbalaz,项目名称:test,代码行数:34,代码来源:view.py


示例14: milestones

def milestones(milestones, default_sort=None, **kwargs):
    if default_sort is None:
        default_sort = sorting.milestone_time
    sorts = {_("by date"): sorting.milestone_time,
             _("alphabetically"): sorting.delegateable_title}
    return NamedPager('milestones', milestones, tiles.milestone.row,
                      sorts=sorts, default_sort=default_sort, **kwargs)
开发者ID:aoeztuerk,项目名称:adhocracy,代码行数:7,代码来源:pager.py


示例15: build_toolbars

    def build_toolbars(self):
        tabs = [
            NavButton(
                _("updates"),
                "/",
            ),
            NavButton(
                _("discussions"),
                "/discussions",
            ),
        ]

        if c.liveupdate_permissions:
            if (c.liveupdate_permissions.allow("settings") or
                    c.liveupdate_permissions.allow("close")):
                tabs.append(NavButton(
                    _("settings"),
                    "/edit",
                ))

            # all contributors should see this so they can leave if they want
            tabs.append(NavButton(
                _("contributors"),
                "/contributors",
            ))

        return [
            NavMenu(
                tabs,
                base_path="/live/" + c.liveupdate_event._id,
                type="tabmenu",
            ),
        ]
开发者ID:reddit,项目名称:reddit-plugin-liveupdate,代码行数:33,代码来源:pages.py


示例16: view

    def view(self, dataset, dimension, format='html'):
        self._get_dataset(dataset)
        try:
            c.dimension = c.dataset[dimension]
        except KeyError:
            abort(404, _('This is not a dimension'))
        if not isinstance(c.dimension, model.Dimension):
            abort(404, _('This is not a dimension'))

        page = self._get_page('page')
        cache = AggregationCache(c.dataset)
        result = cache.aggregate(drilldowns=[dimension], page=page, 
                                 pagesize=PAGE_SIZE)
        items = result.get('drilldown', [])
        c.values = [(d.get(dimension), d.get('amount')) for d in items]

        if format == 'json':
            return to_jsonp({
                "values": c.values,
                "meta": c.dimension.as_dict()})

        c.page = Page(c.values, page=page,
                      item_count=result['summary']['num_drilldowns'],
                      items_per_page=PAGE_SIZE,
                      presliced_list=True)
        return render('dimension/view.html')
开发者ID:doismellburning,项目名称:openspending,代码行数:26,代码来源:dimension.py


示例17: name_validator

def name_validator(val, field=None):
    # check basic textual rules
    min_length = 2
    if len(val) < min_length:
        raise formalchemy.ValidationError(_('Name must be at least %s characters long') % min_length)
    if not name_match.match(val):
        raise formalchemy.ValidationError(_('Name must be purely lowercase alphanumeric (ascii) characters and these symbols: -_'))
开发者ID:AdamJensen-dk,项目名称:ckan-drupal,代码行数:7,代码来源:common.py


示例18: menus

    def menus(self):
        res = []
        if (self.where in ('overview', 'submitted', 'comments')):
            res.append(ProfileSortMenu(default = self.sort))
            if self.sort not in ("hot", "new"):
                res.append(TimeMenu(default = self.time))
        if self.where == 'saved' and c.user.gold:
            srnames = LinkSavesBySubreddit.get_saved_subreddits(self.vuser)
            srnames += CommentSavesBySubreddit.get_saved_subreddits(self.vuser)
            srs = Subreddit._by_name(srnames)
            srnames = [name for name, sr in srs.iteritems()
                            if sr.can_view(c.user)]
            srnames = sorted(list(set(srnames)), key=lambda name: name.lower())
            if len(srnames) > 1:
                sr_buttons = [NavButton(_('all'), None, opt='sr',
                                        css_class='primary')]
                for srname in srnames:
                    sr_buttons.append(NavButton(srname, srname, opt='sr'))
                base_path = request.path
                sr_menu = NavMenu(sr_buttons, base_path=base_path,
                                  title=_('filter by subreddit'),
                                  type='lightdrop')
                res.append(sr_menu)
        elif (self.where == 'gilded' and
                (c.user == self.vuser or c.user_is_admin)):
            path = '/user/%s/gilded/' % self.vuser.name
            buttons = [NavButton(_("my posts"), dest='/'),
                       NavButton(_("posts gilded by me"), dest='/given')]
            res.append(NavMenu(buttons, base_path=path, type='flatlist'))

        return res
开发者ID:aburan28,项目名称:reddit,代码行数:31,代码来源:listingcontroller.py


示例19: package_name_validator

def package_name_validator(key, data, errors, context):
    model = context["model"]
    session = context["session"]
    package = context.get("package")

    query = session.query(model.Package.name).filter_by(name=data[key])
    if package:
        package_id = package.id
    else:
        package_id = data.get(key[:-1] + ("id",))
    if package_id and package_id is not missing:
        query = query.filter(model.Package.id <> package_id)
    result = query.first()
    if result:
        errors[key].append(_('That URL is already in use.'))

    value = data[key]
    if len(value) < PACKAGE_NAME_MIN_LENGTH:
        raise Invalid(
            _('Name "%s" length is less than minimum %s') % (value, PACKAGE_NAME_MIN_LENGTH)
        )
    if len(value) > PACKAGE_NAME_MAX_LENGTH:
        raise Invalid(
            _('Name "%s" length is more than maximum %s') % (value, PACKAGE_NAME_MAX_LENGTH)
        )
开发者ID:code4sac,项目名称:ckan,代码行数:25,代码来源:validators.py


示例20: tag_delete

def tag_delete(context, data_dict):
    '''Delete a tag.

    You must be a sysadmin to delete tags.

    :param id: the id or name of the tag
    :type id: string
    :param vocabulary_id: the id or name of the vocabulary that the tag belongs
        to (optional, default: None)
    :type vocabulary_id: string

    '''
    model = context['model']

    if not data_dict.has_key('id') or not data_dict['id']:
        raise ValidationError({'id': _('id not in data')})
    tag_id_or_name = _get_or_bust(data_dict, 'id')

    vocab_id_or_name = data_dict.get('vocabulary_id')

    tag_obj = model.tag.Tag.get(tag_id_or_name, vocab_id_or_name)

    if tag_obj is None:
        raise NotFound(_('Could not find tag "%s"') % tag_id_or_name)

    _check_access('tag_delete', context, data_dict)

    tag_obj.delete()
    model.repo.commit()
开发者ID:LeadsPlus,项目名称:ckan,代码行数:29,代码来源:delete.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python i18n.get_lang函数代码示例发布时间:2022-05-25
下一篇:
Python g.reset_caches函数代码示例发布时间: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