当前位置: 首页>>代码示例>>Python>>正文


Python component.getUtility函数代码示例

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


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

示例1: update_links

def update_links(event):
    obj = event.object
    if is_outdated(obj) or not is_publically_visible(obj):
        return
    temporary = hasattr(obj, 'meta_type') and \
        obj.meta_type == TempFolder.meta_type
    if temporary:
        # Objects that are temporary (read: portal_factory) and do not have a
        # (stable) URL (yet) do not need to be crawled: relative links will be
        # off quickly and we can't really use the UID anyway.
        return
    try:
        link_checker = getToolByName(obj, 'portal_linkchecker').aq_inner
    except AttributeError:
        return
    if not link_checker.active:
        return
    retriever = IRetriever(obj, None)
    if retriever is not None:
        sm = getSecurityManager()
        if not sm.checkPermission(ModifyPortalContent, obj):
            return
        if (not IReferenceable.providedBy(obj)):
            return
        async = getUtility(IAsyncService)
        tpath = '/'.join(obj.getPhysicalPath())
        job = async.queueJob(retrieve_async, obj, tpath, online=True)
        callback = job.addCallbacks(failure=job_failure_callback)
        callback  # for pep
开发者ID:EU-OSHA,项目名称:osha.policy,代码行数:29,代码来源:handlers.py

示例2: items

    def items(self):
        request = self.request
        catalog = getUtility(ICatalog)

        results = getUtility(ICatalog).searchResults(
            traversablePath={'any_of':(self.context,)},
            typeType={'any_of': ('User Manuals',)},
            sort_order='reverse', sort_on='modified',
            isDraft={'any_of': (False,)})

        for item in results:
            url = absoluteURL(item, request)

            preview = getMultiAdapter((item, request), IContentPreview)
            preview.update()

            info = {
                'title': item.title,
                'description': item.description,
                'guid': '%s/'%url,
                'pubDate': rfc822.formatdate(time.mktime(
                        IDCTimes(item).modified.timetuple())),
                'isPermaLink': True}

            principal = IOwnership(item).owner
            if principal is not None:
                profile = IPersonalProfile(principal)
                info['author'] = u'%s (%s)'%(profile.email, profile.title)

            yield info
开发者ID:Zojax,项目名称:zojax.usermanual,代码行数:30,代码来源:feeds.py

示例3: setupAdminClient

def setupAdminClient(portal, event):
    client = queryUtility(IAdminClient)
    if client is None:
        settings = getUtility(IRegistry)

        try:
            jid = settings['jarn.xmpp.adminJID']
            jdomain = settings['jarn.xmpp.xmppDomain']
            password = settings['jarn.xmpp.adminPassword']
            pubsub_jid = settings['jarn.xmpp.pubsubJID']
        except KeyError:
            return

        client = AdminClient(jid, jdomain, password, pubsub_jid)
        gsm = getGlobalSiteManager()
        gsm.registerUtility(client, IAdminClient)

        def checkAdminClientConnected():
            if client.state != 'authenticated':
                logger.error('XMPP admin client has not been able to authenticate. ' \
                    'Client state is "%s". Will retry on the next request.' % client.state)
                gsm.unregisterUtility(client, IAdminClient)

        zr = getUtility(IZopeReactor)
        zr.reactor.callLater(10, checkAdminClientConnected)
开发者ID:AbdAllah-Ahmed,项目名称:jarn.xmpp.core,代码行数:25,代码来源:startup.py

示例4: setUp

    def setUp(self):
        self.portal = self.layer['portal']
        self.portal_url = self.portal.portal_url()
        # create EasyNewsletter instance and add some subscribers
        setRoles(self.portal, TEST_USER_ID, ['Manager'])
        login(self.portal, TEST_USER_NAME)
        self.portal._original_MailHost = self.portal.MailHost
        self.portal.MailHost = mailhost = MockMailHost('MailHost')
        sm = getSiteManager(context=self.portal)
        sm.unregisterUtility(provided=IMailHost)
        sm.registerUtility(mailhost, provided=IMailHost)
        self.mail_host = getUtility(IMailHost)

        if not IS_PLONE_5:  # BBB
            self.portal.email_from_address = "[email protected]"
            self.portal.email_from_name = u"Plone Master"
            self.mail_host.smtp_host = u"example.com"
            self.mail_host.smtp_port = 25
            self.mail_host.smtp_userid = u"[email protected]"
            self.mail_host.smtp_pass = u"Password"
        else:
            self.registry = getUtility(IRegistry)
            reg_mail = self.registry.forInterface(
                IMailSchema, prefix='plone')
            reg_mail.email_from_address = '[email protected]'
            reg_mail.email_from_name = u'Plone Master'
            reg_mail.smtp_host = u'example.com'
            reg_mail.smtp_port = 25
            reg_mail.smtp_userid = u'[email protected]'
            reg_mail.smtp_pass = u'Password'
开发者ID:collective,项目名称:Products.EasyNewsletter,代码行数:30,代码来源:test_utils.py

示例5: run

    def run(self):

        self.text_content=None
        self.new_headers={}
        things=self.headers

        extractor=getUtility(IExtractor, name='extractor')
        ext_data=extractor.extract(self.content, things)

        ext_things={}
        ext_things.update(things)
        ext_things.update(ext_data)

        content_extractor=getUtility(IExtractor, name='content')
        cont_data=content_extractor.extract(self.content, ext_things)

        if not 'text-body' in cont_data:
            recoll_extractor=getUtility(IExtractor, name='recoll')
            ext_things.update(cont_data)
            cont_data=recoll_extractor.extract(self.content, ext_things)

        text_p=things['text-body-presence']='text-body' in cont_data

        ext_things.update(cont_data)

        if text_p:
            self.text_content=cont_data['text-body'].encode('utf-8')
            storage=getUtility(IContentStorage, name="content")
            ext_things['text-id']=storage.hash(self.text_content)

        self.new_headers=ext_things
开发者ID:CellulaProject,项目名称:icc.cellula,代码行数:31,代码来源:tasks.py

示例6: onZSliceValueChanged

    def onZSliceValueChanged(self, evt):

        try:
            component.getUtility(ICurrentImage)
        except:
            # no image loaded so exit early
            return

        # get current z-slice index
        self.SetZIndexValue(int(round(evt.GetSliceValue())))

        # we'd like to give regular plot updates without bring the system
        # to it's knees - we'll guarantee the user a redraw at least every
        # half second
        dt = time.time() - self._last_delayed_redraw

        # schedule an update in 0.25 second
        if self._delayed_cb:
            self._delayed_cb.cancel()

        if dt > 1.0:
            # perform redraw immediately
            self.doScheduledRedraw()
        else:
            # schedule for later
            self._delayed_cb = reactor.callLater(0.25, self.doScheduledRedraw)
开发者ID:andyTsing,项目名称:MicroView,代码行数:26,代码来源:SpectrumPlotWindow.py

示例7: update

 def update(self):
     quiz = getSite()
     int_ids = getUtility(IQreatureIntIds, context=self.context)
     ce = getUtility(ICounterExplorer, context=self.context)
     results= [r for r in quiz.values() if IQuizResult.providedBy(r)]
     self.titles = [r.title.encode('utf-8') for r in results]
     self.counters = [ce.getCounter(r, key=int_ids.getId(r)) for r in results]
开发者ID:HengeSense,项目名称:Qreature,代码行数:7,代码来源:result.py

示例8: countResults

def countResults(event):
    ce = getUtility(ICounterExplorer,context=event.result)
    int_ids = getUtility(IQreatureIntIds, context = event.result)
    res_id = int_ids.getId(event.result)
    print '************the key which goes to explorer**************'
    print res_id
    ce.incrementCounter(event.result,res_id)
开发者ID:HengeSense,项目名称:Qreature,代码行数:7,代码来源:handlers.py

示例9: createLineItem

    def createLineItem(self, data):
        parent = self.aq_parent
        utility = getUtility( IShoppingCartUtility )
        cart = utility.get(parent, create=True)

        intids = getUtility(IIntIds)
        iid = intids.queryId(parent)
        if iid is None:
            iid = intids.register(parent)

        nitem = PayableLineItem()
        nitem.item_id = parent.UID() # archetypes uid
        nitem.uid = iid

        # copy over information regarding the item
        nitem.name = "Supplemental Pharmacy Application"
        nitem.description = "Supplemental Pharmacy Application 2011"
        nitem.cost = float(self.price)
        nitem.quantity = 1
        nitem.product_code = nitem.item_id
        
        nitem.data = data
 
        # add to cart
        if nitem.item_id not in cart.keys():
            cart[nitem.item_id] = nitem
            cart.last_item = nitem.item_id        
开发者ID:ianderso,项目名称:getpaid.pfgbuyableadapter,代码行数:27,代码来源:buyableformadapter.py

示例10: isAvailable

    def isAvailable(self):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            return False

        principal = self.context.__principal__
        principalId = principal.id

        if self.request.principal.id == principalId:
            return False

        invitations = [
            invitation.object.id for invitation in
            getUtility(IInvitations).getInvitationsByPrincipal(
                principalId, ('invitation.member',))]

        for group in getUtility(ICatalog).searchResults(
            type = {'any_of': ('content.group',)},
            members = {'any_of': (self.request.principal.id,)}):

            if group.id in invitations:
                continue

            if principalId not in group.members and \
                    checkPermission('zojax.InviteGroupMember', group):
                return True

        return False
开发者ID:Zojax,项目名称:zojax.groups,代码行数:27,代码来源:invitation.py

示例11: validate

 def validate(self, data):
     """Check that user is not attempting to merge a person into itself."""
     dupe_person = data.get('dupe_person')
     target_person = data.get('target_person') or self.user
     if dupe_person is None:
         self.setFieldError(
             'dupe_person', 'The duplicate is not a valid person or team.')
     else:
         if dupe_person == target_person:
             self.addError(_("You can't merge ${name} into itself.",
                   mapping=dict(name=dupe_person.name)))
         dupe_person_ppas = getUtility(IArchiveSet).getPPAOwnedByPerson(
             dupe_person, statuses=[ArchiveStatus.ACTIVE,
                                    ArchiveStatus.DELETING])
         if dupe_person_ppas is not None:
             self.addError(_(
                 "${name} has a PPA that must be deleted before it "
                 "can be merged. It may take ten minutes to remove the "
                 "deleted PPA's files.",
                 mapping=dict(name=dupe_person.name)))
         all_branches = getUtility(IAllBranches)
         if not all_branches.ownedBy(dupe_person).isPrivate().is_empty():
             self.addError(
                 _("${name} owns private branches that must be "
                   "deleted or transferred to another owner first.",
                 mapping=dict(name=dupe_person.name)))
         if dupe_person.isMergePending():
             self.addError(_("${name} is already queued for merging.",
                   mapping=dict(name=dupe_person.name)))
     if target_person is not None and target_person.isMergePending():
         self.addError(_("${name} is already queued for merging.",
               mapping=dict(name=target_person.name)))
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:32,代码来源:peoplemerge.py

示例12: continue_action

    def continue_action(self, action, data):
        dupeaccount = data['dupe_person']
        if dupeaccount == self.user:
            # Please, don't try to merge you into yourself.
            return

        emails = getUtility(IEmailAddressSet).getByPerson(dupeaccount)
        emails_count = emails.count()
        if emails_count > 1:
            # The dupe account have more than one email address. Must redirect
            # the user to another page to ask which of those emails (s)he
            # wants to claim.
            self.next_url = '+requestmerge-multiple?dupe=%d' % dupeaccount.id
            return

        assert emails_count == 1
        email = emails[0]
        login = getUtility(ILaunchBag).login
        logintokenset = getUtility(ILoginTokenSet)
        # Need to remove the security proxy because the dupe account may have
        # hidden email addresses.
        token = logintokenset.new(
            self.user, login, removeSecurityProxy(email).email,
            LoginTokenType.ACCOUNTMERGE)
        token.sendMergeRequestEmail()
        self.next_url = './+mergerequest-sent?dupe=%d' % dupeaccount.id
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:26,代码来源:peoplemerge.py

示例13: test_unsubscribe_pillar_artifacts_specific_info_types

    def test_unsubscribe_pillar_artifacts_specific_info_types(self):
        # Only remove subscriptions for bugs of the specified info type.

        person_grantee = self.factory.makePerson(name='grantee')

        owner = self.factory.makePerson(name='pillarowner')
        pillar = self.factory.makeProduct(owner=owner)

        # Make bugs the person_grantee is subscribed to.
        bug1, ignored = self._make_subscribed_bug(
            person_grantee, pillar,
            information_type=InformationType.USERDATA)

        bug2, ignored = self._make_subscribed_bug(
            person_grantee, pillar,
            information_type=InformationType.PRIVATESECURITY)

        # Now run the job, removing access to userdata artifacts.
        getUtility(IRemoveArtifactSubscriptionsJobSource).create(
            pillar.owner, pillar=pillar,
            information_types=[InformationType.USERDATA])
        with block_on_job(self):
            transaction.commit()

        self.assertNotIn(
            person_grantee, removeSecurityProxy(bug1).getDirectSubscribers())
        self.assertIn(
            person_grantee, removeSecurityProxy(bug2).getDirectSubscribers())
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:28,代码来源:test_sharingjob.py

示例14: copy_fields

    def copy_fields(self, translation):
        fti = getUtility(IDexterityFTI, name=self.context.portal_type)
        schemas = []
        schemas.append(fti.lookupSchema())

        for behavior_schema in \
                utils.getAdditionalSchemata(self.context, self.context.portal_type):
            if behavior_schema is not None:
                schemas.append(behavior_schema)

        for schema in schemas:
            for field_name in schema:
                if field_name in EXCLUDES:
                    continue
                if not ILanguageIndependentField.providedBy(schema[field_name]):
                    value = getattr(schema(self.context), field_name, _marker)
                    if IRelationValue.providedBy(value):
                        obj = value.to_object
                        adapter = queryAdapter(translation, ILanguage)
                        trans_obj = ITranslationManager(obj).get_translation(adapter.get_language())
                        if trans_obj:
                            intids = component.getUtility(IIntIds)
                            value = RelationValue(intids.getId(trans_obj))
                    if not (value == _marker):
                        # We check if not (value == _marker) because z3c.relationfield has an __eq__
                        setattr(schema(translation), field_name, value)
开发者ID:oikoumene,项目名称:wcc.multilingual,代码行数:26,代码来源:multilingual.py

示例15: update

    def update(self):
        self.everyone = getUtility(IEveryoneGroup).id
        self.authgroup = getUtility(IAuthenticatedGroup).id

        manager = IPrincipalPermissionManager(removeSecurityProxy(self.context))

        if 'site.access.save' in self.request:
            val = self.request.get('site.access', None)
            if val == 'open':
                manager.grantPermissionToPrincipal(
                    'zojax.AccessSite', self.everyone)
                manager.unsetPermissionForPrincipal(
                    'zojax.AccessSite', self.authgroup)

            if val == 'private':
                manager.grantPermissionToPrincipal(
                    'zojax.AccessSite', self.authgroup)
                manager.unsetPermissionForPrincipal(
                    'zojax.AccessSite', self.everyone)

            IStatusMessage(self.request).add(
                _('Site access settings has been changed.'))

        self.everyoneAllowed = manager.getSetting(
            'zojax.AccessSite', self.everyone) is Allow

        self.authgroupAllowed = manager.getSetting(
            'zojax.AccessSite', self.authgroup) is Allow
开发者ID:Zojax,项目名称:zojax.site,代码行数:28,代码来源:access.py


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