本文整理汇总了Python中zope.component.hooks.getSite函数的典型用法代码示例。如果您正苦于以下问题:Python getSite函数的具体用法?Python getSite怎么用?Python getSite使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getSite函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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')
示例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')
示例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()
示例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 ''
示例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
示例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]
示例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))
示例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())
示例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"
示例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"
示例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))
示例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
示例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
示例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