本文整理匯總了Python中zope.component.getUtility方法的典型用法代碼示例。如果您正苦於以下問題:Python component.getUtility方法的具體用法?Python component.getUtility怎麽用?Python component.getUtility使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類zope.component
的用法示例。
在下文中一共展示了component.getUtility方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def __init__(self, name, context, request, location, count=9,\
size_type=['original', 'compressed'],\
source_type=['album', 'camera'], **kw):
FormInput.__init__(self, name, **kw)
self.context = context
self.request = request
self.upload_url = location.absolute_url(self.request) + "/@@wechat_upload"
self.field_name = name
self.count = count
self.size_type = size_type
self.source_type= source_type
self.items = []
for i in self.value:
img_obj = getUtility(IIntIds).queryObject(int(i))
scr = img_obj.transformed_url(mime='image/x-thumbnail-png', subfile='image_tile')
url = img_obj.transformed_url(mime='image/x-thumbnail-png', subfile='image_large')
self.items.append({'intid':i, 'src': scr, 'url':url})
示例2: _global_roles_for
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def _global_roles_for(self, principal):
"""On a principal (user/group) get global roles."""
roles = {}
groups = getUtility(IGroups)
if self.principal and principal == self.principal.id:
# Its the actual user id
# We return all the global roles (including group)
roles = self.principal.roles.copy()
for group in self.principal.groups:
roles.update(groups.get_principal(group).roles)
return roles
# We are asking for group id so only group roles
if groups:
group = groups.get_principal(principal)
return group.roles.copy()
示例3: _global_permissions_for
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def _global_permissions_for(self, principal, permission):
"""On a principal (user + group) get global permissions."""
groups = getUtility(IGroups)
if self.principal and principal == self.principal.id:
# Its the actual user
permissions = self.principal.permissions.copy()
if permission in permissions:
return level_setting_as_boolean('p', permissions[permission])
for group in self.principal.groups:
permissions = groups.get_principal(principal).permissions
if permission in permissions:
return level_setting_as_boolean('p', permissions[permission])
if groups:
# Its a group
permissions = groups.get_principal(principal).permissions
if permission in permissions:
return level_setting_as_boolean('p', permissions[permission])
return None
示例4: test_add_sync_utility
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def test_add_sync_utility(self):
util = getUtility(IQueueUtility)
var = []
async def printHi():
var.append('hola')
context = self.layer.app['plone'].conn.root()
v = AsyncMockView(context, self.layer.app['plone'].conn, printHi, self.layer.app)
loop = asyncio.get_event_loop()
future = asyncio.run_coroutine_threadsafe(util.add(v), loop)
future2 = asyncio.run_coroutine_threadsafe(util.add(v), loop)
total = future.result()
total = future2.result()
future = asyncio.run_coroutine_threadsafe(util._queue.join(), loop)
total = future.result() # noqa
self.assertTrue('hola' in var)
self.assertTrue(len(var) == 2)
示例5: get_user_info
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def get_user_info(context, request):
"""Return information about the logged in user.
"""
result = {}
groups = set()
principal = IInteraction(request).principal
result[principal.id] = {
'roles': principal.roles,
'groups': principal.groups,
'properties': principal.properties
}
groups.update(principal.groups)
group_search = getUtility(IGroups)
result['groups'] = {}
for group in groups:
group_object = group_search.get_principal(group)
result['groups'][group_object.id] = {
'roles': group_object.roles,
'groups': group_object.groups
}
return result
示例6: run
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def run(self, arguments, settings, app):
app_settings['root_user']['password'] = TESTING_SETTINGS['root_user']['password']
root = getUtility(IApplication, name='root')
interact('''
plone.server interactive shell
==============================
Available local variables:
- app
- root
- app_settings
''', local={
'app': app,
'root': root,
'app_settings': app_settings
})
示例7: add_behavior
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def add_behavior(self, iface):
"""We need to apply the marker interface.
value: Interface to add
"""
if isinstance(iface, str):
name = iface
elif Interface.providedBy(iface):
name = iface.__identifier__
else:
raise AttributeError('Cant identify Interface')
behavior_registration = getUtility(IBehavior, name=name)
if behavior_registration is not None and\
behavior_registration.interface(self) is not None:
# We can adapt so we can apply this dynamic behavior
self.__behaviors__ |= {name}
if behavior_registration.marker is not None:
alsoProvides(self, behavior_registration.marker)
示例8: content_type_negotiation
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def content_type_negotiation(request, resource, view):
# We need to check for the language
accept = None
if 'ACCEPT' in request.headers:
accept = request.headers['ACCEPT']
if IDownloadView.providedBy(view) or accept in (None, '*/*'):
# if download view, we want to render raw immediately
# or if no or */* accept header provided
return IRendererFormatRaw
np = getUtility(IContentNegotiation, 'content_type')
ap = np.negotiate(accept=accept)
# We need to check for the accept
if str(ap.content_type) in app_settings['renderers']:
return app_settings['renderers'][str(ap.content_type)]
else:
log.info('Could not find content type {} renderer'.format(
str(ap.content_type)))
return IRendererFormatRaw
示例9: language_negotiation
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def language_negotiation(request):
# We need to check for the language
if 'ACCEPT-LANGUAGE' in request.headers:
accept_lang = request.headers['ACCEPT-LANGUAGE']
else:
accept_lang = 'en'
np = getUtility(IContentNegotiation, 'language')
ap = np.negotiate(accept_language=accept_lang)
# We need to check for the accept
if ap is None:
language = app_settings['languages']['en']
else:
language = app_settings['languages'][str(ap.language)]
return language
示例10: test_add_new_field_to_configlet
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def test_add_new_field_to_configlet(self):
title = u'Add new field to configlet'
step = self.get_upgrade_step(title)
self.assertIsNotNone(step)
from collective.lazysizes.interfaces import ILazySizesSettings
from plone.registry.interfaces import IRegistry
from zope.component import getUtility
registry = getUtility(IRegistry)
# simulate state on previous version
record = ILazySizesSettings.__identifier__ + '.css_class_blacklist'
del registry.records[record]
with self.assertRaises(KeyError):
registry.forInterface(ILazySizesSettings)
# execute upgrade step and verify changes were applied
self.execute_upgrade_step(step)
settings = registry.forInterface(ILazySizesSettings)
self.assertTrue(hasattr(settings, 'css_class_blacklist'))
self.assertEqual(settings.css_class_blacklist, set([]))
示例11: transformIterable
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def transformIterable(self, result, encoding):
registry = getUtility(IRegistry)
settings = registry.forInterface(ILazySizesSettings, check=False)
# we apply the transform always for anonymous users
if not api.user.is_anonymous():
# user is authenticated, check if transform is enabled
enabled = getattr(settings, 'lazyload_authenticated', False)
if not enabled:
return # no need to transform
result = self._parse(result)
if result is None:
return
css_class_blacklist = getattr(settings, 'css_class_blacklist', set())
blacklist = self._blacklist(result, css_class_blacklist)
path = '{0}//img|{0}//iframe|{0}//blockquote'.format(ROOT_SELECTOR)
for el in result.tree.xpath(path):
if el in blacklist:
continue
self._lazyload(el)
return result
示例12: verifyStore
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def verifyStore():
"""Ensure that the patch level in the database matches the application.
@raise RuntimeError: Raised if there are unknown or unapplied patches.
"""
from fluiddb.schema.main import createSchema
from fluiddb.scripts.schema import getPatchStatus
schema = createSchema()
zstorm = getUtility(IZStorm)
store = zstorm.get('main')
try:
status = getPatchStatus(store, schema)
if status.unappliedPatches:
patches = ', '.join('patch_%d' % version
for version in status.unappliedPatches)
raise RuntimeError('Database has unapplied patches: %s' % patches)
if status.unknownPatches:
patches = ', '.join('patch_%d' % version
for version in status.unknownPatches)
raise RuntimeError('Database has unknown patches: %s' % patches)
finally:
zstorm.remove(store)
store.close()
示例13: setUp
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def setUp(cls):
# Aio HTTP app
cls.aioapp = make_app(settings=TESTING_SETTINGS)
# Plone App Object
cls.app = getUtility(IApplication, name='root')
cls.db = cls.app['plone']
include(cls.app.app.config, 'testing.zcml', sys.modules['plone.server'])
cls.app.app.config.execute_actions()
load_cached_schema()
示例14: resource_directory
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def resource_directory(_context, name, directory):
if directory:
directory = osPath(_context.path(directory))
if not directory.is_dir():
raise ConfigurationError('No such directory', directory)
root = getUtility(IApplication, 'root')
if name not in root:
# prevent circular import
from plone.server.content import StaticDirectory
root[name] = StaticDirectory(directory)
示例15: _set_data
# 需要導入模塊: from zope import component [as 別名]
# 或者: from zope.component import getUtility [as 別名]
def _set_data(self, data):
if 'size' in self.__dict__:
del self.__dict__['size']
# Search for a storable that is able to store the data
dottedName = '.'.join((data.__class__.__module__,
data.__class__.__name__))
storable = getUtility(IStorage, name=dottedName)
storable.store(data, self._blob)