本文整理汇总了Python中zope.component.getUtility函数的典型用法代码示例。如果您正苦于以下问题:Python getUtility函数的具体用法?Python getUtility怎么用?Python getUtility使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getUtility函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: feedtopciquestion
def feedtopciquestion(obj,event):
"""关注话题有问题"""
intids = getUtility(IIntIds)
intid = intids.getId(obj)
catalog = component.getUtility(ICatalog)
qtlist = sorted(catalog.findRelations({'from_id': intid}))
if len(qtlist) == 0: return
for q in qtlist:
topiclist = IFollowing(q.to_object).followed
catalog = getToolByName(obj, 'portal_catalog')
for topic in topiclist:
brain = catalog({'object_provides': Ifeedsfolder.__identifier__,
'Creator': topic,
'sort_on': 'sortable_title'})
if not brain:
break
folder = brain[0].getObject()
if not folder:
break
id = obj.getId()
feed = catalog({'object_provides': Ifeed.__identifier__,
'id': id,
'path': dict(query='/'.join(folder.getPhysicalPath()),
depth=1),
'sort_on': 'sortable_title'})
"""如果存在当前记录,重置修改时间,否则新建"""
if len(feed) > 0:
feed[0].getObject().type = 1
feed[0].getObject().setModificationDate(DateTime())
else:
item = createContentInContainer(folder,"emc.kb.feed",checkConstraints=False,id=id)
item.type = 1
开发者ID:adam139,项目名称:emc.kb,代码行数:34,代码来源:feed.py
示例17: test_editProperties
def test_editProperties(self):
# https://bugs.launchpad.net/zope-cmf/+bug/174246
# PropertiesTool.editProperties fails with traceback due to
# faulty invocation of the site's manage_changeProperties method
props = { 'email_from_name' : 'Test Admin'
, 'email_from_address' : '[email protected]'
, 'description' : 'Test MailHost Description'
, 'title' : 'Test MailHost'
, 'smtp_server' : 'mail.example.com'
, 'validate_email' : True
, 'email_charset' : 'iso-8859-15'
, 'default_charset' : 'iso-8859-1'
, 'enable_permalink' : True
}
tool = getUtility(IPropertiesTool)
tool.editProperties(props)
site_prop = self.site.getProperty
self.assertEquals(getUtility(IMailHost).smtp_host, 'mail.example.com')
self.assertEquals(site_prop('email_from_name'), 'Test Admin')
self.assertEquals(site_prop('email_from_address'), '[email protected]')
self.assertEquals(site_prop('description'), 'Test MailHost Description')
self.assertEquals(site_prop('title'), 'Test MailHost')
self.assertEquals(site_prop('validate_email'), True)
self.assertEquals(site_prop('email_charset'), 'iso-8859-15')
self.assertEquals(site_prop('default_charset'), 'iso-8859-1')
self.assertEquals(site_prop('enable_permalink'), True)
开发者ID:CGTIC,项目名称:Plone_SP,代码行数:27,代码来源:test_PropertiesTool.py
示例18: get_ttw_fields
def get_ttw_fields(obj):
"""Returns names of the fields that were added to obj through the web"""
fti = getUtility(IDexterityFTI, name=obj.portal_type)
full_schema = fti.lookupSchema()
all_fields = schema.getFieldsInOrder(full_schema)
schema_policy = getUtility(ISchemaPolicy, name=fti.schema_policy)
original_schema = schema_policy.bases(None, None)[0]
original_fields = schema.getFieldsInOrder(original_schema)
new_fields = [field[0] for field in all_fields
if field[0] not in dict(original_fields).keys()]
for behavior_id in fti.behaviors:
behavior = getUtility(IBehavior, behavior_id).interface
if behavior == IContactDetails or not IFormFieldProvider.providedBy(behavior):
continue
try:
default_fieldset_fields = non_fieldset_fields(behavior)
behavior_name = behavior_id.split('.')[-1]
# @TODO: get generic method to get widget id
new_fields.extend(['%s.%s' % (behavior_name, field_name)
for field_name in default_fieldset_fields])
except:
pass
return new_fields
开发者ID:cedricmessiant,项目名称:collective.contact.core,代码行数:27,代码来源:utils.py
示例19: __bind__
def __bind__(self, principal):
clone = super(PasswordPreference, self).__bind__(principal)
clone.user = getUtility(IAuthentication).getUser(principal.id)
clone.ptool = getUtility(IPasswordTool)
#clone.changer = IPasswordChanger(clone.__principal__, None)
return clone
开发者ID:fafhrd91,项目名称:memphis-dev,代码行数:7,代码来源:preferences.py
示例20: get_proposal
def get_proposal(self):
"""Return the proposal to which this document belongs.
This may return a "proposal" or a "submitted proposal".
"""
parent = aq_parent(aq_inner(self))
if IProposal.providedBy(parent):
return parent
# Find submitted proposal when self is an excerpt document in the
# meeting dossier.
for relation in getUtility(ICatalog).findRelations({
'to_id': getUtility(IIntIds).getId(aq_inner(self)),
'from_attribute': 'excerpts'}):
# We expect that there are 0 or 1 relation, because this document
# cannot be the excerpt of multiple proposals.
submitted_proposal = relation.from_object
if api.user.has_permission('View', obj=submitted_proposal):
return submitted_proposal
# Find proposal when self is an excerpt in the case dossier.
generated_excerpts = GeneratedExcerpt.query.by_document(self).all()
if generated_excerpts:
proposal = generated_excerpts[0].proposal.resolve_proposal()
if api.user.has_permission('View', obj=proposal):
return proposal
return None
开发者ID:lukasgraf,项目名称:opengever.core,代码行数:28,代码来源:base.py
注:本文中的zope.component.getUtility函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论