本文整理汇总了Python中zope.component.hooks.getSite函数的典型用法代码示例。如果您正苦于以下问题:Python getSite函数的具体用法?Python getSite怎么用?Python getSite使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getSite函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: upgrade
def upgrade(context):
# Move the Storage to catalog
storage = getUtility(IMultilingualStorage)
canonicals = storage.get_canonicals()
already_added_canonicals = []
generator = queryUtility(IUUIDGenerator)
for canonical in canonicals.keys():
canonical_object = canonicals[canonical]
canonical_languages = canonical_object.get_keys()
if id(canonical_object) not in already_added_canonicals:
tg = generator()
for canonical_language in canonical_languages:
obj = uuidToObject(canonical_object.get_item(canonical_language))
if obj is not None:
IMutableTG(obj).set(tg)
obj.reindexObject()
already_added_canonicals.append(id(canonical_object))
# Uninstall the utility
getSite().getSiteManager().unregisterUtility(storage, IMultilingualStorage)
del storage
# Install the index and rebuild
pcatalog = getToolByName(context, 'portal_catalog', None)
if pcatalog is not None:
indexes = pcatalog.indexes()
if 'TranslationGroup' not in indexes:
pcatalog.addIndex('TranslationGroup', 'FieldIndex')
pcatalog.manage_reindexIndex(ids=['TranslationGroup'])
else:
pcatalog.clearFindAndRebuild()
transaction.commit()
开发者ID:Gomez,项目名称:plone.multilingual,代码行数:30,代码来源:to03.py
示例2: time_based_intids
def time_based_intids():
"""To ensure predictable IntIds in tests, this context manager patches
the IntIds utility so that IntIds are created based on the current time
"""
original_intids = getUtility(IIntIds)
class TimeBasedIntIds(type(original_intids)):
def __init__(self):
self.__dict__ = original_intids.__dict__
def _generateId(self):
intid = int(datetime.now(pytz.UTC).strftime('10%H%M%S00'))
while intid in self.refs:
intid += 1
return intid
globals()['TimeBasedIntIds'] = TimeBasedIntIds
patched_intids = TimeBasedIntIds()
getSite().getSiteManager().registerUtility(patched_intids, IIntIds)
try:
yield
finally:
getSite().getSiteManager().registerUtility(original_intids, IIntIds)
globals().pop('TimeBasedIntIds')
开发者ID:4teamwork,项目名称:opengever.core,代码行数:25,代码来源:helpers.py
示例3: incrementing_intids
def incrementing_intids(starting_number=99000):
"""In testing environments we often want to have predictable intids,
but using a time based version may not work well when time is frozen.
This implementation replaces the intids generator with an incrementing one.
"""
original_intids = getUtility(IIntIds)
counter = {'number': starting_number}
class IncrementingIntIds(type(original_intids)):
def __init__(self):
self.__dict__ = original_intids.__dict__
def _generateId(self):
counter['number'] += 1
intid = counter['number']
while intid in self.refs:
intid += 1
return intid
globals()['IncrementingIntIds'] = IncrementingIntIds
patched_intids = IncrementingIntIds()
getSite().getSiteManager().registerUtility(patched_intids, IIntIds)
try:
yield
finally:
getSite().getSiteManager().registerUtility(original_intids, IIntIds)
globals().pop('IncrementingIntIds')
开发者ID:4teamwork,项目名称:opengever.core,代码行数:28,代码来源:helpers.py
示例4: _dump_zodb_to
def _dump_zodb_to(self, zodbDB, stack):
"""Dump the zodbDB into a data.fs by constructing a FileStorage database
and copying the transactions from the DemoStorage.
"""
ori_site_manager_bases = None
if getSite():
# The __bases__ of our local persistent component registry is
# probably a volatile site manager. Pickling it will corrupt the
# database.
# Therefore we remember the stack bases and remove the __bases__
# for the duration of the DB dump.
ori_site_manager_bases = getSite().getSiteManager().__bases__
self.data['site_site_manager_bases'][str(stack['path'].name)] = [
base.__name__ for base in ori_site_manager_bases
]
getSite().getSiteManager().__bases__ = ()
transaction.commit() # Make sure we have the latest state.
# The transaction records in testing have no _extension set, causing
# a RuntimeError when copied to a filestorage.
map(lambda record: setattr(record, '_extension', record.extension),
zodbDB.storage.iterator())
zodb_file = str(stack['path'].joinpath('zodb.fs'))
blob_dir = str(stack['path'].joinpath('blobs'))
cache_storage = FileStorage(zodb_file, create=True,
blob_dir=blob_dir)
copyTransactionsFromTo(zodbDB.storage, cache_storage)
if ori_site_manager_bases is not None:
# Restore the __bases__ of the local persistent component registry,
# which've removed above.
getSite().getSiteManager().__bases__ = ori_site_manager_bases
transaction.commit()
开发者ID:lukasgraf,项目名称:opengever.core,代码行数:34,代码来源:cached_testing.py
示例5: addToCart
def addToCart( self ):
# create a line item and add it to the cart
item_factory = component.getMultiAdapter( (self.cart, self.context),
interfaces.ILineItemFactory )
# check quantity from request
qty = int(self.request.get('quantity', 1))
try:
item_factory.create(quantity=qty)
except interfaces.AddRecurringItemException:
came_from = self.request.environ.get('HTTP_REFERER',
getSite().absolute_url())
msg = "Your shopping cart already has items in it. \
A recurring payment item may not be added until \
you check out or delete the existing items."
IStatusMessage(self.request).addStatusMessage(msg, type='error')
self.request.response.redirect(came_from)
return ''
except interfaces.RecurringCartItemAdditionException:
came_from = self.request.environ.get('HTTP_REFERER',
getSite().absolute_url())
msg = "Your shopping cart already holds a recurring payment. \
Please purchase the current item or delete it from your \
cart before adding addtional items."
IStatusMessage(self.request).addStatusMessage(msg, type='error')
self.request.response.redirect(came_from)
return ''
开发者ID:affinitic,项目名称:Products.PloneGetPaid,代码行数:28,代码来源:cart.py
示例6: write_workflow
def write_workflow(self, specification_path, output_formatter=None):
specification = self._get_specification(
specification_path, output_formatter=output_formatter)
if not specification:
return False
generator = getUtility(IWorkflowGenerator)
try:
generator(self._workflow_id(specification_path),
specification)
except ConflictError:
raise
except Exception, exc:
if not output_formatter:
raise
getSite().error_log.raising(sys.exc_info())
output_formatter(
'error',
_(u'error_while_generating_workflow',
default=u'${id}: Error while generating'
u' the workflow: ${msg}',
mapping={'msg': str(exc).decode('utf-8'),
'id': self._workflow_id(specification_path)}))
return False
开发者ID:4teamwork,项目名称:ftw.lawgiver,代码行数:25,代码来源:updater.py
示例7: pop_from_tmpstorage
def pop_from_tmpstorage(obj):
# Copy the conversation from the portal (tmpstorage) to the object
annotations = IAnnotations(obj)
annotations[ANNOTATION_KEY] = IConversation(getSite())
IConversation(obj).__parent__ = obj
# Delete the conversation on the portal (tmpstorage)
portal_ann = IAnnotations(getSite())
del portal_ann[ANNOTATION_KEY]
开发者ID:tisto,项目名称:plone.app.discussion,代码行数:8,代码来源:tmpstorage.py
示例8: test_register_once_per_connection
def test_register_once_per_connection(self):
once = maintenance.register_once_per_connection
self.assertTrue(once('/test', getSite(), 1))
self.assertFalse(once('/test', getSite(), 1))
self.assertFalse(once('/test2', getSite(), 1))
self.assertEqual(1, len(maintenance._clockservers))
开发者ID:4teamwork,项目名称:seantis.reservation,代码行数:8,代码来源:test_maintenance.py
示例9: test_isolate_sitehook
def test_isolate_sitehook(self):
setSite(self.layer['portal'])
with isolate_sitehook():
self.assertIsNone(None, getSite())
setSite(PloneSite('fakesite'))
self.assertEquals(self.layer['portal'], getSite())
开发者ID:4teamwork,项目名称:ftw.testbrowser,代码行数:8,代码来源:test_driver_utils.py
示例10: __init__
def __init__(self, *args, **kwargs):
base.Renderer.__init__(self, *args, **kwargs)
try:
self.news_item = getSite()["news"]["feed"].queryCatalog(batch=True, b_size=1)[0].getObject()
except IndexError:
self.news_item = None
self.news_url = getSite()["news"].absolute_url()
self.news_rss_url = self.news_url + "/feed/RSS"
开发者ID:Rudd-O,项目名称:declinefm.policy,代码行数:8,代码来源:latestnews.py
示例11: __init__
def __init__(self, *args, **kwargs):
base.Renderer.__init__(self, *args, **kwargs)
try:
self.archives_item = getSite()["archives"]["feed"].queryCatalog(batch=True, b_size=1)[0].getObject()
except IndexError:
self.archives_item = None
self.archives_url = getSite()["archives"].absolute_url()
self.archives_rss_url = self.archives_url + "/feed/itunes.xml"
self.archives_itunes_url = "itpc:" + self.archives_url.split(":",1)[1] + "/feed/itunes.xml"
开发者ID:Rudd-O,项目名称:declinefm.policy,代码行数:9,代码来源:latestshow.py
示例12: register_event_recorder
def register_event_recorder(*required):
"""Register a generic event subscriber for recording certain events.
In order to be able to use the testbrowser, the transaction must be able to
synchronize the threads. The easiest way to do that is to store the infos
in the database. We do that by just attaching them to the Plone site.
"""
getSite().getSiteManager().registerHandler(
recording_event_subscriber, list(required))
开发者ID:4teamwork,项目名称:opengever.core,代码行数:9,代码来源:event_recorder.py
示例13: solrSearchResults
def solrSearchResults(request=None, **keywords):
""" perform a query using solr after translating the passed in
parameters with portal catalog semantics """
search = queryUtility(ISearch)
config = queryUtility(ISolrConnectionConfig)
if request is None:
# try to get a request instance, so that flares can be adapted to
# ploneflares and urls can be converted into absolute ones etc;
# however, in this case any arguments from the request are ignored
request = getattr(getSite(), 'REQUEST', None)
args = deepcopy(keywords)
elif IHTTPRequest.providedBy(request):
args = deepcopy(request.form) # ignore headers and other stuff
args.update(keywords) # keywords take precedence
else:
assert isinstance(request, dict), request
args = deepcopy(request)
args.update(keywords) # keywords take precedence
# if request is a dict, we need the real request in order to
# be able to adapt to plone flares
request = getattr(getSite(), 'REQUEST', args)
if 'path' in args and 'navtree' in args['path']:
raise FallBackException # we can't handle navtree queries yet
use_solr = args.get('use_solr', False) # A special key to force Solr
if not use_solr and config.required:
required = set(config.required).intersection(args)
if required:
for key in required:
if not args[key]:
raise FallBackException
else:
raise FallBackException
schema = search.getManager().getSchema() or {}
params = cleanupQueryParameters(extractQueryParameters(args), schema)
languageFilter(args)
prepareData(args)
mangleQuery(args, config, schema)
query = search.buildQuery(**args)
if query != {}:
optimizeQueryParameters(query, params)
__traceback_info__ = (query, params, args)
response = search(query, **params)
else:
return SolrResponse()
def wrap(flare):
""" wrap a flare object with a helper class """
adapter = queryMultiAdapter((flare, request), IFlare)
return adapter is not None and adapter or flare
results = response.results()
for idx, flare in enumerate(results):
flare = wrap(flare)
for missing in set(schema.stored).difference(flare):
flare[missing] = MV
results[idx] = wrap(flare)
padResults(results, **params) # pad the batch
return response
开发者ID:jean,项目名称:collective.solr,代码行数:56,代码来源:dispatcher.py
示例14: _get_catalogs
def _get_catalogs(obj):
try:
uid_catalog = getToolByName(obj, config.UID_CATALOG)
except AttributeError:
uid_catalog = getToolByName(getSite(), config.UID_CATALOG)
try:
ref_catalog = getToolByName(obj, config.REFERENCE_CATALOG)
except AttributeError:
ref_catalog = getToolByName(getSite(), config.REFERENCE_CATALOG)
return uid_catalog, ref_catalog
开发者ID:plone,项目名称:plone.app.referenceablebehavior,代码行数:10,代码来源:uidcatalog.py
示例15: _load_state
def _load_state(self):
self._loaded = True
self.uid = getuid(self.context)
self.portal = getSite()
altportal = getSite()
self.sender = invitation_sender(self.portal)
self.localize = getToolByName(self.portal, 'translation_service')
self.timefn = self.localize.ulocalized_time
if HAS_PAE:
self.timefn = ulocalized_time # fixed DateTime timezone bug
开发者ID:upiq,项目名称:collective.inviting,代码行数:10,代码来源:message.py
示例16: get_obj_by_relative_path
def get_obj_by_relative_path(relative_path):
"""Returns the object by a path relative to the site root.
If no object is found, None is returned.
Bad acquisition lookups are eliminiated.
"""
site_path = '/'.join(getSite().getPhysicalPath())
obj_path = '/'.join((site_path, relative_path.strip('/')))
obj = getSite().restrictedTraverse(obj_path, None)
if not obj or '/'.join(obj.getPhysicalPath()) != obj_path:
return None
return obj
开发者ID:4teamwork,项目名称:ftw.publisher.core,代码行数:11,代码来源:utils.py
示例17: action_join
def action_join(self, action, data):
self.handle_join_success(data)
if data.has_key('email'):
if data['email'].endswith('ilo.org'):
return self.request.response.redirect(getSite().absolute_url() +
'/registration_successful')
else:
return self.request.response.redirect(getSite().absolute_url() +
'/registration_success')
开发者ID:ploneUN,项目名称:eval.registration,代码行数:11,代码来源:register.py
示例18: translated_portal_type
def translated_portal_type(self):
request = getSite().REQUEST
portal_types = getToolByName(getSite(), 'portal_types')
fti = portal_types.get(self.attrs['portal_type'], None)
default = translate(self.attrs['portal_type'], domain='plone',
context=request)
if fti:
return translate(fti.title, domain=fti.i18n_domain,
default=default,
context=request)
return default
开发者ID:4teamwork,项目名称:ftw.activity,代码行数:11,代码来源:record.py
示例19: pathcu
def pathcu(self):
folderc = getSite().unrestrictedTraverse('actividades/coloquio')
foldersem = getSite().unrestrictedTraverse('actividades/seminarios')
folderspe = getSite().unrestrictedTraverse('actividades/actividades-especiales/cu')
return [
'/'.join(folderc.getPhysicalPath()),
'/'.join(foldersem.getPhysicalPath()),
'/'.join(folderspe.getPhysicalPath()),
]
开发者ID:imatem,项目名称:matem.event,代码行数:12,代码来源:views.py
示例20: get_specification
def get_specification(workflow_id):
discovery = getMultiAdapter((getSite(), getSite().REQUEST),
IWorkflowSpecificationDiscovery)
parser = getUtility(IWorkflowSpecificationParser)
for path in discovery.discover():
if os.path.basename(os.path.dirname(path)) != workflow_id:
continue
with open(path) as specfile:
return parser(specfile, path=path, silent=True)
return None
开发者ID:4teamwork,项目名称:ftw.lawgiver,代码行数:13,代码来源:utils.py
注:本文中的zope.component.hooks.getSite函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论