Getting the portal easy and quick

plone.api.portal get the portal walking the path until it find ISiteRoot instead of using getMultiAdapter. The call is not cached but the portal object cannot change inside a DX Root Object. Could this cached with @forever.memoize? Generally speaking, could we cache the portal somewhere? What is the best way to get the portal object? The plone_portal_state view cache it (@memoize) it but to get the view we still have to do a traverse.

Actually, I'm doing this in the browser view:

@memoize 
def portal_state(self):
    return getMultiAdapter((self.context, self.request), name=u'plone_portal_state')

in my addon but seems too much to me. I mean, getMultiAdapter query a zope object which, starting from context and request, search for a suitabile interface implementer (IPortalState). Is this quite fast or it is better to cache it? I would cache it forever (but for Plone Site) but maybe there are cases where getting the portal must return None?

Thanks for any clarification.

I use mostly

from zope.component.hooks import getSite

portal = getSite()

Background: on initial publishers traversal an event is fired and a handler sets the site (the portal root) as a thread local variable, which is read by getSite - see code at zope.component/hooks.py at master · zopefoundation/zope.component · GitHub for details.

I think it is relative fast (even if thread local variables are not that fast to access). Getting the site manager to lookup adapters does the same in the process, so the pure direct access is probably faster.

1 Like

Using getSite also has the advantage that it will still work correctly if there are multiple Plone sites in the same Zope instance.

1 Like

Is this because every thread run on a single request (request url -> traversal -> site set)? This means the site thread local variable is set at every request, then used by the python code.

Thanks both for the hint.

And what about portal_state? I would use portal.restrictedTraverse('@@portal_state') because the multiadapter has no adapting in practice.

This is probably the slowest method.

Yes, this happens on every request anyway.