How to use adapters to implement a feature

I was right: the adapter is 3 times faster than the helper browser view:


class AMPView(BrowserView):
    """Accelerated Mobile Pages default view."""
    ...
    @property
    def pixel(self):
        adapter = queryAdapter(self.context, IAMPPixelProvider)
        if adapter is not None:
            return adapter.pixel()

    @property
    def amp_tracking_pixel(self):
        return api.content.get_view('amp-tracking-pixel', self.context, self.request)()

class AMPTrackingPixel(BrowserView):
    def __call__(self):
        return u'<amp-pixel src="https://example.com/tracker/foo" layout="nodisplay"></amp-pixel>'
  <browser:page
      class=".AMPTrackingPixel"
      for="plone.dexterity.interfaces.IDexterityContent"
      layer="collective.behavior.amp.interfaces.IAddOnLayer"
      name="amp-tracking-pixel"
      permission="zope2.View"
      />
from profilehooks import timecall
...
class AMPViewTestCase(unittest.TestCase):
    ...
    def test_adapter(self):
        @timecall(immediate=True)
        def render(times):
            for i in xrange(0, times):
                self.view.pixel
        render(times=1000)

    def test_helper_view(self):
        @timecall(immediate=True)
        def render(times):
            for i in xrange(0, times):
                self.view.amp_tracking_pixel
        render(times=1000)
$ bin/test -m performance
Running collective.behavior.amp.testing.collective.behavior.amp:Integration tests:
...
collective.behavior.amp.testing.collective.behavior.amp:Integration in 0.000 seconds.
  Running:
    1/2 (50.0%)
  render (/home/hvelarde/collective/behavior.amp/src/collective/behavior/amp/tests/test_performance.py:23):
    0.022 seconds

    2/2 (100.0%)
  render (/home/hvelarde/collective/behavior.amp/src/collective/behavior/amp/tests/test_performance.py:30):
    0.073 seconds

                
  Ran 2 tests with 0 failures and 0 errors in 0.382 seconds.
...
3 Likes