[Zope3-checkins] SVN: Zope3/branches/roger-contentprovider/src/zope/contentprovider/ Implemented Gary's sub-view requirements for the content provider API.

Stephan Richter srichter at cosmos.phy.tufts.edu
Mon Oct 24 22:59:27 EDT 2005


Log message for revision 39606:
  Implemented Gary's sub-view requirements for the content provider API. 
  These final changes should address the final outstanding concerns. Once I 
  fixed the zope.viewlet package, I will merge this code to the trunk.
  
  So, Gary, Roger and anyone interested in this code, please review those 
  final changes!
  
  

Changed:
  U   Zope3/branches/roger-contentprovider/src/zope/contentprovider/README.txt
  U   Zope3/branches/roger-contentprovider/src/zope/contentprovider/interfaces.py
  U   Zope3/branches/roger-contentprovider/src/zope/contentprovider/tales.py
  U   Zope3/branches/roger-contentprovider/src/zope/contentprovider/tests.py

-=-
Modified: Zope3/branches/roger-contentprovider/src/zope/contentprovider/README.txt
===================================================================
--- Zope3/branches/roger-contentprovider/src/zope/contentprovider/README.txt	2005-10-24 22:04:59 UTC (rev 39605)
+++ Zope3/branches/roger-contentprovider/src/zope/contentprovider/README.txt	2005-10-25 02:59:26 UTC (rev 39606)
@@ -5,8 +5,8 @@
 This package provides a framework to develop componentized Web GUI
 applications. Instead of describing the content of a page using a single
 template or static system of templates and METAL macros, content provider
-objects can be created that are dynamically looked up based on the
-setup/configuration of the application.
+objects are dynamically looked up based on the setup/configuration of the
+application.
 
   >>> from zope.contentprovider import interfaces
 
@@ -28,8 +28,8 @@
 Looking up views for a particular content component and a request just simply
 does not work by itself. The content inside the page is still monolithic. One
 attempt to solve this problem are METAL macros, which allow you to insert
-other TAL snippets into your main template. But macros have two shortcomings;
-for one there is a "hard-coded" one-to-one mapping between a slot and the
+other TAL snippets into your main template. But macros have two shortcomings.
+For one there is a "hard-coded" one-to-one mapping between a slot and the
 macro that fills that slot, which makes it impossible to register several
 macros for a given location. The second problem is that macros are not views
 in their own right; thus they cannot provide functionality that is independent
@@ -52,10 +52,10 @@
 into page templates and user interface design. Zope is commonly known to
 reinvent the wheel, develop its own terminology and misuse other's terms. For
 example, the Plone community has a very different understanding of what a
-"portlet" is than what is commonly accepted in the corporate world, which
-derives its definition from JSR 168. Therefore an additional use case of the
-design of this package was to stick with common terms and use them in their
-original meaning -- well, given a little extra twist.
+"portlet" is compared to the commonly accepted meaning in the corporate world,
+which derives its definition from JSR 168. Therefore an additional use case of
+the design of this package was to stick with common terms and use them in
+their original meaning -- well, given a little extra twist.
 
 The most basic user interface component in the Web application Java world is
 the "content provider" [1]_. A content provider is simply responsible for
@@ -90,12 +90,17 @@
 Content Providers
 -----------------
 
-Content Providers is a term from the Java world that refers to components that
+Content Provider is a term from the Java world that refers to components that
 can provide HTML content. It means nothing more! How the content is found and
 returned is totally up to the implementation. The Zope 3 touch to the concept
 is that content providers are multi-adapters that are looked up by the
 context, request (and thus the layer/skin), and view they are displayed in.
 
+The second important concept of content providers are their two-phase
+rendering design. In the first phase the state of the content provider is
+prepared and, if applicable, any data, the provider is responsible for, is
+updated.
+
 So let's create a simple content provider:
 
   >>> import zope.interface
@@ -110,30 +115,182 @@
   ...     message = u'My Message'
   ...
   ...     def __init__(self, context, request, view):
+  ...         self.__parent__ = view
+  ...
+  ...     def update(self):
   ...         pass
   ...
-  ...     def __call__(self):
+  ...     def render(self):
   ...         return u'<div class="box">%s</div>' %self.message
 
-The interface requires us to make the content provider callable. We can now
-instantiate the content provider (manually) and render it:
+The ``update()`` method is executed during phase one. Since no state needs to
+be calculated and no data is modified by this simple content provider, it is
+an empty implementation. The ``render()`` method implements phase 2 of the
+process. We can now instantiate the content provider (manually) and render it:
 
   >>> box = MessageBox(None, None, None)
-  >>> box()
+  >>> box.render()
   u'<div class="box">My Message</div>'
 
 Since our content provider did not require the context, request or view to
 create its HTML content, we were able to pass trivial dummy values into the
-constructor.
+constructor. Also note that the provider must have a parent (using the
+``__parent__`` attribute) specified at all times. The parent must be the view
+the provider appears in.
 
-I agree, this functionally does not seem very useful now. The constructor
-seems useless and the returned content is totally static. However, we
-implemented a contract for content providers that other code can rely
-on. Content providers are (commonly) instantiated using the context, request
-and view they appear in and are required to always generate its HTML using
-those three components.
+I agree, this functionally does not seem very useful now. The constructor and
+the ``update()`` method seem useless and the returned content is totally
+static. However, we implemented a contract for content providers that other
+code can rely on. Content providers are (commonly) instantiated using the
+context, request and view they appear in and are required to always generate
+its HTML using those three components.
 
 
+Two-Phased Content Providers
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Let's now have a look at a content provider that actively uses the two-phase
+rendering process. The simpler scenario is the case where the content provider
+updates a content component without affecting anything else. So let's create a
+content component to be updated,
+
+  >>> class Article(object):
+  ...     title = u'initial'
+  >>> article = Article()
+
+and the content provider that is updating the title:
+
+  >>> class ChangeTitle(object):
+  ...     zope.interface.implements(interfaces.IContentProvider)
+  ...     zope.component.adapts(zope.interface.Interface,
+  ...                           browser.IDefaultBrowserLayer,
+  ...                           zope.interface.Interface)
+  ...     fieldName = 'ChangeTitle.title'
+  ...
+  ...     def __init__(self, context, request, view):
+  ...         self.__parent__ = view
+  ...         self.context, self.request = context, request
+  ...
+  ...     def update(self):
+  ...         if self.fieldName in self.request:
+  ...             self.context.title = self.request[self.fieldName]
+  ...
+  ...     def render(self):
+  ...         return u'<input name="%s" value="%s" />' % (self.fieldName,
+  ...                                                     self.context.title)
+
+Using a request, let's now instantiate the content provider and go through the
+two-phase rendering process:
+
+  >>> from zope.publisher.browser import TestRequest
+  >>> request = TestRequest()
+  >>> changer = ChangeTitle(article, request, None)
+  >>> changer.update()
+  >>> changer.render()
+  u'<input name="ChangeTitle.title" value="initial" />'
+
+Let's now enter a new title and render the provider:
+
+  >>> request = TestRequest(form={'ChangeTitle.title': u'new title'})
+  >>> changer = ChangeTitle(article, request, None)
+  >>> changer.update()
+  >>> changer.render()
+  u'<input name="ChangeTitle.title" value="new title" />'
+  >>> article.title
+  u'new title'
+
+So this was easy. Let's now look at a case where one content provider's update
+influences the content of another. Let's say we have a content provider that
+displays the article's title:
+
+  >>> class ViewTitle(object):
+  ...     zope.interface.implements(interfaces.IContentProvider)
+  ...     zope.component.adapts(zope.interface.Interface,
+  ...                           browser.IDefaultBrowserLayer,
+  ...                           zope.interface.Interface)
+  ...
+  ...     def __init__(self, context, request, view):
+  ...         self.context, self.__parent__ = context, view
+  ...
+  ...     def update(self):
+  ...         pass
+  ...
+  ...     def render(self):
+  ...         return u'<h1>Title: %s</h1>' % self.context.title
+
+Let's now say that the `ShowTitle` content provider is shown on a page
+*before* the `ChangeTitle` content provider. If we do the full rendering
+process for each provider in sequence, we get the wrong result:
+
+  >>> request = TestRequest(form={'ChangeTitle.title': u'newer title'})
+
+  >>> viewer = ViewTitle(article, request, None)
+  >>> viewer.update()
+  >>> viewer.render()
+  u'<h1>Title: new title</h1>'
+
+  >>> changer = ChangeTitle(article, request, None)
+  >>> changer.update()
+  >>> changer.render()
+  u'<input name="ChangeTitle.title" value="newer title" />'
+
+So the correct way of doing this is to first complete phase 1 (update) for all
+providers, before executing phase 2 (render):
+
+  >>> request = TestRequest(form={'ChangeTitle.title': u'newest title'})
+
+  >>> viewer = ViewTitle(article, request, None)
+  >>> changer = ChangeTitle(article, request, None)
+
+  >>> viewer.update()
+  >>> changer.update()
+
+  >>> viewer.render()
+  u'<h1>Title: newest title</h1>'
+
+  >>> changer.render()
+  u'<input name="ChangeTitle.title" value="newest title" />'
+
+
+``UpdateNotCalled`` Errors
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Since calling ``update()`` before any other method that mutates the provider
+or any other data is so important to the correct functioning of the API, the
+developer has the choice to raise the ``UpdateNotCalled`` error, if any method
+is called before ``update()`` (with exception of the constructor):
+
+  >>> class InfoBox(object):
+  ...     zope.interface.implements(interfaces.IContentProvider)
+  ...     zope.component.adapts(zope.interface.Interface,
+  ...                           browser.IDefaultBrowserLayer,
+  ...                           zope.interface.Interface)
+  ...
+  ...     def __init__(self, context, request, view):
+  ...         self.__parent__ = view
+  ...         self.__updated = False
+  ...
+  ...     def update(self):
+  ...         self.__updated = True
+  ...
+  ...     def render(self):
+  ...         if not self.__updated:
+  ...             raise interfaces.UpdateNotCalled
+  ...         return u'<div>Some information</div>'
+
+  >>> info = InfoBox(None, None, None)
+
+  >>> info.render()
+  Traceback (most recent call last):
+  ...
+  UpdateNotCalled: ``update()`` was not called yet.
+
+  >>> info.update()
+
+  >>> info.render()
+  u'<div>Some information</div>'
+
+
 The TALES ``provider`` Expression
 ---------------------------------
 
@@ -311,7 +468,7 @@
   ...     zope.interface.implements(IMessageType)
   ...     type = None
   ...
-  ...     def __call__(self):
+  ...     def render(self):
   ...         return u'<div class="box,%s">%s</div>' %(self.type, self.message)
 
   >>> zope.component.provideAdapter(

Modified: Zope3/branches/roger-contentprovider/src/zope/contentprovider/interfaces.py
===================================================================
--- Zope3/branches/roger-contentprovider/src/zope/contentprovider/interfaces.py	2005-10-24 22:04:59 UTC (rev 39605)
+++ Zope3/branches/roger-contentprovider/src/zope/contentprovider/interfaces.py	2005-10-25 02:59:26 UTC (rev 39606)
@@ -23,34 +23,90 @@
 from zope.app.publisher.interfaces import browser
 
 
+class IUpdateNotCalled(zope.interface.common.interfaces.IRuntimeError):
+    """Update Not Called
+
+    An error that is raised when any content provider method is called before
+    the ``update()`` method.
+    """
+
+class UpdateNotCalled(RuntimeError):
+    pass
+
+# Make it a singelton
+UpdateNotCalled = UpdateNotCalled('``update()`` was not called yet.')
+
 class IContentProvider(browser.IBrowserView):
     """A piece of content to be shown on a page.
 
     Objects implementing this interface are providing HTML content when they
-    are called. It is up to the implementation to decide how to lookup
+    are rendered. It is up to the implementation to decide how to lookup
     necessary data to complete the job.
 
+    Content Providers use a two-stage process to fulfill their contract:
+
+    (1) The first stage is responsible to calculate the state of the content
+        provider and, if applicable, edit the data. This stage is executed
+        using the ``update()`` method.
+
+    (2) During the second stage the provider constructs/renders its HTML
+        output based on the state that was calculated in the first stage. This
+        stage is executed using the ``render()`` method.
+
     Content Providers are discriminated by three components: the context, the
     request and the view. This allows great control over the selection of the
     provider.
     """
 
-    view = zope.interface.Attribute(
-        """The View
+    __parent__ = zope.interface.Attribute(
+        """The view the provider appears in.
 
         The view is the third discriminator of the content provider. It allows
         that the content can be controlled for different views.
+
+        Having it stored as the parent is also very important for the security
+        context to be kept.
         """)
 
-    def __call__(*args, **kw):
-        """ Return the content provided by this content provider.
+    def update():
+        """Initialize the content provider.
+
+        This method should perform all state calculation and *not* refer it to
+        the rendering stage.
+
+        In this method, all state must be calculated from the current
+        interaction (e.g., the browser request); all contained or managed
+        content providers must have ``update()`` be called as well; any
+        additional stateful API for contained or managed content providers
+        must be handled; and persistent objects should be modified, if the
+        provider is going to do it.
+
+        Do *not* store state about persistent objects: the rendering process
+        should actually use the persistent objects for the data, in case other
+        components modify the object between the update and render stages.
+
+        This method *must* be called before any other method that mutates the
+        instance (besides the class constructor). Non-mutating methods and
+        attributes may raise an error if used before ``update()`` is
+        called. The view may rely on this order but is *not required* to
+        explicitly enforce this. Implementations *may* enforce it as a
+        developer aid.
         """
 
+    def render(*args, **kw):
+        """Return the content provided by this content provider.
+
+        Calling this method before ``update()`` *may* (but is not required to)
+        raise an ``UpdateNotCalled`` error.
+        """
+
+
 class IContentProviderType(zope.interface.interfaces.IInterface):
     """Type interface for content provider types (interfaces derived from
        IContentProvider).
     """
 
+
 class ITALNamespaceData(zope.interface.interfaces.IInterface):
     """A type interface that marks an interface as a TAL data specification.
 
@@ -59,6 +115,7 @@
     content provider can have multiple interfaces that are of this type.
     """
 
+
 class ContentProviderLookupError(zope.component.ComponentLookupError):
     """No content provider was found."""
 

Modified: Zope3/branches/roger-contentprovider/src/zope/contentprovider/tales.py
===================================================================
--- Zope3/branches/roger-contentprovider/src/zope/contentprovider/tales.py	2005-10-24 22:04:59 UTC (rev 39605)
+++ Zope3/branches/roger-contentprovider/src/zope/contentprovider/tales.py	2005-10-25 02:59:26 UTC (rev 39606)
@@ -38,8 +38,16 @@
 
 
 class TALESProviderExpression(expressions.StringExpr):
-    """Collect content provider via a TAL namespace."""
+    """Collect content provider via a TAL namespace.
 
+    Note that this implementation of the TALES `provider` namespace does not
+    work with interdependent content providers, since each content-provider's
+    stage one call is made just before the second stage is executed. If you
+    want to implement interdependent content providers, you need to consider a
+    TAL-independent view implementation that will complete all content
+    providers' stage one before rendering any of them.
+    """
+
     zope.interface.implements(interfaces.ITALESProviderExpression)
 
     def __call__(self, econtext):
@@ -59,4 +67,8 @@
         # Insert the data gotten from the context
         addTALNamespaceData(provider, econtext)
 
-        return provider()
+        # Stage 1: Do the state update.
+        provider.update()
+
+        # Stage 2: Render the HTML content.
+        return provider.render()

Modified: Zope3/branches/roger-contentprovider/src/zope/contentprovider/tests.py
===================================================================
--- Zope3/branches/roger-contentprovider/src/zope/contentprovider/tests.py	2005-10-24 22:04:59 UTC (rev 39605)
+++ Zope3/branches/roger-contentprovider/src/zope/contentprovider/tests.py	2005-10-25 02:59:26 UTC (rev 39606)
@@ -56,8 +56,9 @@
 def tearDown(test):
     setup.placefulTearDown()
     os.path.getmtime = mtime_func
+    global counter
+    counter = 0
 
-
 def test_suite():
     return unittest.TestSuite((
         DocFileSuite('README.txt',



More information about the Zope3-Checkins mailing list