1Metadata-Version: 1.0 2Name: zope.contentprovider 3Version: 3.7.2 4Summary: Content Provider Framework for Zope Templates 5Home-page: http://pypi.python.org/pypi/zope.contentprovider 6Author: Zope Foundation and Contributors 7Author-email: zope-dev@zope.org 8License: ZPL 2.1 9Description: ================= 10 Content Providers 11 ================= 12 13 This package provides a framework to develop componentized Web GUI 14 applications. Instead of describing the content of a page using a single 15 template or static system of templates and METAL macros, content provider 16 objects are dynamically looked up based on the setup/configuration of the 17 application. 18 19 .. contents:: 20 21 Motivation and Design Goals 22 --------------------------- 23 24 Before diving into the features of this package let me take up a few bytes of 25 text to explain the use cases that drove us to develop this package (also 26 others) and how the API documented below fulfills/solves those use cases. When 27 we started developing Zope 3, it was from a desire to decentralize 28 functionality and thus the complexity of the Python code. And we were 29 successful! The component architecture is a marvelous piece of software that 30 hopefully will allow us to build scalable solutions for a very long 31 time. However, when it comes to user interface design, in this case 32 specifically HTML pages, we have failed to provide the features and patterns 33 of assembeling a page from configured components. 34 35 Looking up views for a particular content component and a request just simply 36 does not work by itself. The content inside the page is still monolithic. One 37 attempt to solve this problem are METAL macros, which allow you to insert 38 other TAL snippets into your main template. But macros have two shortcomings. 39 For one there is a "hard-coded" one-to-one mapping between a slot and the 40 macro that fills that slot, which makes it impossible to register several 41 macros for a given location. The second problem is that macros are not views 42 in their own right; thus they cannot provide functionality that is independent 43 of the main template's view. 44 45 A second approach to modular UI design are rendering pipes. Rendering pipes 46 have the great advantage that they can reach all regions of the page during 47 every step of the rendering process. For example, if we have a widget in the 48 middle of the page that requires some additional Javascript, then it is easy 49 for a rendering unit to insert the Javascript file link in the HTML header of 50 the page. This type of use case is very hard to solve using page 51 templates. However, pipes are not the answer to componentized user interface, 52 since they cannot simply deal with registering random content for a given page 53 region. In fact, I propose that pipelines are orthogonal to content providers, 54 the concept introducted below. A pipeline framework could easily use 55 functionality provided by this and other packages to provide component-driven 56 UI design. 57 58 So our goal is clear: Bring the pluggability of the component architecture 59 into page templates and user interface design. Zope is commonly known to 60 reinvent the wheel, develop its own terminology and misuse other's terms. For 61 example, the Plone community has a very different understanding of what a 62 "portlet" is compared to the commonly accepted meaning in the corporate world, 63 which derives its definition from JSR 168. Therefore an additional use case of 64 the design of this package was to stick with common terms and use them in 65 their original meaning -- well, given a little extra twist. 66 67 The most basic user interface component in the Web application Java world is 68 the "content provider" [1]_. A content provider is simply responsible for 69 providing HTML content for a page. This is equivalent to a view that does not 70 provide a full page, but just a snippet, much like widgets or macros. Once 71 there is a way to configure those content providers, we need a way to 72 insert them into our page templates. In our implementation this is 73 accomplished using a new TALES namespace that allows to insert content 74 providers by name. But how, you might wonder, does this provide a 75 componentized user interface? On the Zope 3 level, each content provider is 76 registered as a presentation component discriminated by the context, request 77 and view it will appear in. Thus different content providers will be picked 78 for different configurations. 79 80 Okay, that's pretty much everything there is to say about content 81 providers. What, we are done? Hold on, what about defining regions of pages 82 and filling them configured UI snippets. The short answer is: See the 83 ``zope.viewlet`` pacakge. But let me also give you the long answer. This and 84 the other pacakges were developed using real world use cases. While doing 85 this, we noticed that not every project would need, for example, all the 86 features of a portlet, but would still profit from lower-level features. Thus 87 we decided to declare clear boundaries of functionality and providing each 88 level in a different package. This particualr package is only meant to provide 89 the interface between the content provider world and page templates. 90 91 .. [1] Note that this is a bit different from the role named content provider, 92 which refers to a service that provides content; the content provider 93 we are talking about here are the software components the service would 94 provide to an application. 95 96 97 Content Providers 98 ----------------- 99 100 Content Provider is a term from the Java world that refers to components that 101 can provide HTML content. It means nothing more! How the content is found and 102 returned is totally up to the implementation. The Zope 3 touch to the concept 103 is that content providers are multi-adapters that are looked up by the 104 context, request (and thus the layer/skin), and view they are displayed in. 105 106 The second important concept of content providers are their two-phase 107 rendering design. In the first phase the state of the content provider is 108 prepared and, if applicable, any data the provider is responsible for is 109 updated. 110 111 >>> from zope.contentprovider import interfaces 112 113 So let's create a simple content provider: 114 115 >>> import zope.interface 116 >>> import zope.component 117 >>> from zope.publisher.interfaces import browser 118 119 >>> class MessageBox(object): 120 ... zope.interface.implements(interfaces.IContentProvider) 121 ... zope.component.adapts(zope.interface.Interface, 122 ... browser.IDefaultBrowserLayer, 123 ... zope.interface.Interface) 124 ... message = u'My Message' 125 ... 126 ... def __init__(self, context, request, view): 127 ... self.__parent__ = view 128 ... 129 ... def update(self): 130 ... pass 131 ... 132 ... def render(self): 133 ... return u'<div class="box">%s</div>' %self.message 134 135 The ``update()`` method is executed during phase one. Since no state needs to 136 be calculated and no data is modified by this simple content provider, it is 137 an empty implementation. The ``render()`` method implements phase 2 of the 138 process. We can now instantiate the content provider (manually) and render it: 139 140 >>> box = MessageBox(None, None, None) 141 >>> box.render() 142 u'<div class="box">My Message</div>' 143 144 Since our content provider did not require the context, request or view to 145 create its HTML content, we were able to pass trivial dummy values into the 146 constructor. Also note that the provider must have a parent (using the 147 ``__parent__`` attribute) specified at all times. The parent must be the view 148 the provider appears in. 149 150 I agree, this functionally does not seem very useful now. The constructor and 151 the ``update()`` method seem useless and the returned content is totally 152 static. However, we implemented a contract for content providers that other 153 code can rely on. Content providers are (commonly) instantiated using the 154 context, request and view they appear in and are required to always generate 155 its HTML using those three components. 156 157 158 Two-Phased Content Providers 159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 160 161 Let's now have a look at a content provider that actively uses the two-phase 162 rendering process. The simpler scenario is the case where the content provider 163 updates a content component without affecting anything else. So let's create a 164 content component to be updated, 165 166 >>> class Article(object): 167 ... title = u'initial' 168 >>> article = Article() 169 170 and the content provider that is updating the title: 171 172 >>> class ChangeTitle(object): 173 ... zope.interface.implements(interfaces.IContentProvider) 174 ... zope.component.adapts(zope.interface.Interface, 175 ... browser.IDefaultBrowserLayer, 176 ... zope.interface.Interface) 177 ... fieldName = 'ChangeTitle.title' 178 ... 179 ... def __init__(self, context, request, view): 180 ... self.__parent__ = view 181 ... self.context, self.request = context, request 182 ... 183 ... def update(self): 184 ... if self.fieldName in self.request: 185 ... self.context.title = self.request[self.fieldName] 186 ... 187 ... def render(self): 188 ... return u'<input name="%s" value="%s" />' % (self.fieldName, 189 ... self.context.title) 190 191 Using a request, let's now instantiate the content provider and go through the 192 two-phase rendering process: 193 194 >>> from zope.publisher.browser import TestRequest 195 >>> request = TestRequest() 196 >>> changer = ChangeTitle(article, request, None) 197 >>> changer.update() 198 >>> changer.render() 199 u'<input name="ChangeTitle.title" value="initial" />' 200 201 Let's now enter a new title and render the provider: 202 203 >>> request = TestRequest(form={'ChangeTitle.title': u'new title'}) 204 >>> changer = ChangeTitle(article, request, None) 205 >>> changer.update() 206 >>> changer.render() 207 u'<input name="ChangeTitle.title" value="new title" />' 208 >>> article.title 209 u'new title' 210 211 So this was easy. Let's now look at a case where one content provider's update 212 influences the content of another. Let's say we have a content provider that 213 displays the article's title: 214 215 >>> class ViewTitle(object): 216 ... zope.interface.implements(interfaces.IContentProvider) 217 ... zope.component.adapts(zope.interface.Interface, 218 ... browser.IDefaultBrowserLayer, 219 ... zope.interface.Interface) 220 ... 221 ... def __init__(self, context, request, view): 222 ... self.context, self.__parent__ = context, view 223 ... 224 ... def update(self): 225 ... pass 226 ... 227 ... def render(self): 228 ... return u'<h1>Title: %s</h1>' % self.context.title 229 230 Let's now say that the `ShowTitle` content provider is shown on a page 231 *before* the `ChangeTitle` content provider. If we do the full rendering 232 process for each provider in sequence, we get the wrong result: 233 234 >>> request = TestRequest(form={'ChangeTitle.title': u'newer title'}) 235 236 >>> viewer = ViewTitle(article, request, None) 237 >>> viewer.update() 238 >>> viewer.render() 239 u'<h1>Title: new title</h1>' 240 241 >>> changer = ChangeTitle(article, request, None) 242 >>> changer.update() 243 >>> changer.render() 244 u'<input name="ChangeTitle.title" value="newer title" />' 245 246 So the correct way of doing this is to first complete phase 1 (update) for all 247 providers, before executing phase 2 (render): 248 249 >>> request = TestRequest(form={'ChangeTitle.title': u'newest title'}) 250 251 >>> viewer = ViewTitle(article, request, None) 252 >>> changer = ChangeTitle(article, request, None) 253 254 >>> viewer.update() 255 >>> changer.update() 256 257 >>> viewer.render() 258 u'<h1>Title: newest title</h1>' 259 260 >>> changer.render() 261 u'<input name="ChangeTitle.title" value="newest title" />' 262 263 264 ``UpdateNotCalled`` Errors 265 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 266 267 Since calling ``update()`` before any other method that mutates the provider 268 or any other data is so important to the correct functioning of the API, the 269 developer has the choice to raise the ``UpdateNotCalled`` error, if any method 270 is called before ``update()`` (with exception of the constructor): 271 272 >>> class InfoBox(object): 273 ... zope.interface.implements(interfaces.IContentProvider) 274 ... zope.component.adapts(zope.interface.Interface, 275 ... browser.IDefaultBrowserLayer, 276 ... zope.interface.Interface) 277 ... 278 ... def __init__(self, context, request, view): 279 ... self.__parent__ = view 280 ... self.__updated = False 281 ... 282 ... def update(self): 283 ... self.__updated = True 284 ... 285 ... def render(self): 286 ... if not self.__updated: 287 ... raise interfaces.UpdateNotCalled 288 ... return u'<div>Some information</div>' 289 290 >>> info = InfoBox(None, None, None) 291 292 >>> info.render() 293 Traceback (most recent call last): 294 ... 295 UpdateNotCalled: ``update()`` was not called yet. 296 297 >>> info.update() 298 299 >>> info.render() 300 u'<div>Some information</div>' 301 302 303 The TALES ``provider`` Expression 304 --------------------------------- 305 306 The ``provider`` expression will look up the name of the content provider, 307 call it and return the HTML content. The first step, however, will be to 308 register our content provider with the component architecture: 309 310 >>> zope.component.provideAdapter(MessageBox, name='mypage.MessageBox') 311 312 The content provider must be registered by name, since the TALES expression 313 uses the name to look up the provider at run time. 314 315 Let's now create a view using a page template: 316 317 >>> import os, tempfile 318 >>> temp_dir = tempfile.mkdtemp() 319 >>> templateFileName = os.path.join(temp_dir, 'template.pt') 320 >>> open(templateFileName, 'w').write(''' 321 ... <html> 322 ... <body> 323 ... <h1>My Web Page</h1> 324 ... <div class="left-column"> 325 ... <tal:block replace="structure provider:mypage.MessageBox" /> 326 ... </div> 327 ... <div class="main"> 328 ... Content here 329 ... </div> 330 ... </body> 331 ... </html> 332 ... ''') 333 334 As you can see, we exprect the ``provider`` expression to simply look up the 335 content provider and insert the HTML content at this place. 336 337 Next we register the template as a view (browser page) for all objects: 338 339 >>> from zope.browserpage.simpleviewclass import SimpleViewClass 340 >>> FrontPage = SimpleViewClass(templateFileName, name='main.html') 341 342 >>> zope.component.provideAdapter( 343 ... FrontPage, 344 ... (zope.interface.Interface, browser.IDefaultBrowserLayer), 345 ... zope.interface.Interface, 346 ... name='main.html') 347 348 Let's create a content object that can be viewed: 349 350 >>> class Content(object): 351 ... zope.interface.implements(zope.interface.Interface) 352 353 >>> content = Content() 354 355 Finally we look up the view and render it. Note that a 356 BeforeUpdateEvent is fired - this event should always be fired before 357 any contentprovider is updated. 358 359 >>> from zope.publisher.browser import TestRequest 360 >>> events = [] 361 >>> zope.component.provideHandler(events.append, (None, )) 362 >>> request = TestRequest() 363 364 >>> view = zope.component.getMultiAdapter((content, request), 365 ... name='main.html') 366 >>> print view().strip() 367 <html> 368 <body> 369 <h1>My Web Page</h1> 370 <div class="left-column"> 371 <div class="box">My Message</div> 372 </div> 373 <div class="main"> 374 Content here 375 </div> 376 </body> 377 </html> 378 379 >>> events 380 [<zope.contentprovider.interfaces.BeforeUpdateEvent object at ...>] 381 382 The event holds the provider and the request. 383 384 >>> events[0].request 385 <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1> 386 >>> events[0].object 387 <MessageBox object at ...> 388 389 Failure to lookup a Content Provider 390 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 391 392 If the name is not found, an error is raised. To demonstrate this behavior 393 let's create another template: 394 395 >>> errorFileName = os.path.join(temp_dir, 'error.pt') 396 >>> open(errorFileName, 'w').write(''' 397 ... <html> 398 ... <body> 399 ... <tal:block replace="structure provider:mypage.UnknownName" /> 400 ... </body> 401 ... </html> 402 ... ''') 403 404 >>> ErrorPage = SimpleViewClass(errorFileName, name='error.html') 405 >>> zope.component.provideAdapter( 406 ... ErrorPage, 407 ... (zope.interface.Interface, browser.IDefaultBrowserLayer), 408 ... zope.interface.Interface, 409 ... name='main.html') 410 411 >>> errorview = zope.component.getMultiAdapter((content, request), 412 ... name='main.html') 413 >>> print errorview() 414 Traceback (most recent call last): 415 ... 416 ContentProviderLookupError: mypage.UnknownName 417 418 419 Additional Data from TAL 420 ~~~~~~~~~~~~~~~~~~~~~~~~ 421 422 The ``provider`` expression allows also for transferring data from the TAL 423 context into the content provider. This is accomplished by having the content 424 provider implement an interface that specifies the attributes and provides 425 ``ITALNamespaceData``: 426 427 >>> import zope.schema 428 >>> class IMessageText(zope.interface.Interface): 429 ... message = zope.schema.Text(title=u'Text of the message box') 430 431 >>> zope.interface.directlyProvides(IMessageText, 432 ... interfaces.ITALNamespaceData) 433 434 Now the message box can receive its text from the TAL environment: 435 436 >>> class DynamicMessageBox(MessageBox): 437 ... zope.interface.implements(IMessageText) 438 439 >>> zope.component.provideAdapter( 440 ... DynamicMessageBox, provides=interfaces.IContentProvider, 441 ... name='mypage.DynamicMessageBox') 442 443 We are now updating our original template to provide the message text: 444 445 >>> open(templateFileName, 'w').write(''' 446 ... <html> 447 ... <body> 448 ... <h1>My Web Page</h1> 449 ... <div class="left-column"> 450 ... <tal:block define="message string:Hello World!" 451 ... replace="structure provider:mypage.DynamicMessageBox" /> 452 ... <tal:block define="message string:Hello World again!" 453 ... replace="structure provider:mypage.DynamicMessageBox" /> 454 ... </div> 455 ... <div class="main"> 456 ... Content here 457 ... </div> 458 ... </body> 459 ... </html> 460 ... ''') 461 462 Now we should get two message boxes with different text: 463 464 >>> print view().strip() 465 <html> 466 <body> 467 <h1>My Web Page</h1> 468 <div class="left-column"> 469 <div class="box">Hello World!</div> 470 <div class="box">Hello World again!</div> 471 </div> 472 <div class="main"> 473 Content here 474 </div> 475 </body> 476 </html> 477 478 Finally, a content provider can also implement several ``ITALNamespaceData``: 479 480 >>> class IMessageType(zope.interface.Interface): 481 ... type = zope.schema.TextLine(title=u'The type of the message box') 482 483 >>> zope.interface.directlyProvides(IMessageType, 484 ... interfaces.ITALNamespaceData) 485 486 We'll change our message box content provider implementation a bit, so the new 487 information is used: 488 489 >>> class BetterDynamicMessageBox(DynamicMessageBox): 490 ... zope.interface.implements(IMessageType) 491 ... type = None 492 ... 493 ... def render(self): 494 ... return u'<div class="box,%s">%s</div>' %(self.type, self.message) 495 496 >>> zope.component.provideAdapter( 497 ... BetterDynamicMessageBox, provides=interfaces.IContentProvider, 498 ... name='mypage.MessageBox') 499 500 Of course, we also have to make our tempalte a little bit more dynamic as 501 well: 502 503 >>> open(templateFileName, 'w').write(''' 504 ... <html> 505 ... <body> 506 ... <h1>My Web Page</h1> 507 ... <div class="left-column"> 508 ... <tal:block define="message string:Hello World!; 509 ... type string:error" 510 ... replace="structure provider:mypage.MessageBox" /> 511 ... <tal:block define="message string:Hello World again!; 512 ... type string:warning" 513 ... replace="structure provider:mypage.MessageBox" /> 514 ... </div> 515 ... <div class="main"> 516 ... Content here 517 ... </div> 518 ... </body> 519 ... </html> 520 ... ''') 521 522 Now we should get two message boxes with different text and types: 523 524 >>> print view().strip() 525 <html> 526 <body> 527 <h1>My Web Page</h1> 528 <div class="left-column"> 529 <div class="box,error">Hello World!</div> 530 <div class="box,warning">Hello World again!</div> 531 </div> 532 <div class="main"> 533 Content here 534 </div> 535 </body> 536 </html> 537 538 539 Base class 540 ---------- 541 542 The ``zope.contentprovider.provider`` module provides an useful base 543 class for implementing content providers. It has all boilerplate code 544 and it's only required to override the ``render`` method to make it 545 work: 546 547 >>> from zope.contentprovider.provider import ContentProviderBase 548 >>> class MyProvider(ContentProviderBase): 549 ... def render(self, *args, **kwargs): 550 ... return 'Hi there' 551 552 >>> provider = MyProvider(None, None, None) 553 >>> interfaces.IContentProvider.providedBy(provider) 554 True 555 556 >>> provider.update() 557 >>> print provider.render() 558 Hi there 559 560 Note, that it can't be used as is, without providing the ``render`` method: 561 562 >>> bad = ContentProviderBase(None, None, None) 563 >>> bad.update() 564 >>> print bad.render() 565 Traceback (most recent call last): 566 ... 567 NotImplementedError: ``render`` method must be implemented by subclass 568 569 You can add the update logic into the ``update`` method as with any content 570 provider and you can implement more complex rendering patterns, based on 571 templates, using this ContentProviderBase class as a base. 572 573 574 You might also want to look at the ``zope.viewlet`` package for a more 575 featureful API. 576 577 Let's remove all temporary data we created during this README. 578 579 >>> import shutil 580 >>> shutil.rmtree(temp_dir) 581 582 583 ======= 584 CHANGES 585 ======= 586 587 3.7.2 (2010-05-25) 588 ------------------ 589 590 - Fixed unit tests broken under Python 2.4 by the switch to the standard 591 library ``doctest`` module. 592 593 594 3.7.1 (2010-04-30) 595 ------------------ 596 597 - Prefer the standard library's ``doctest`` module to the one from 598 ``zope.testing.`` 599 600 601 3.7 (2010-04-27) 602 ---------------- 603 604 - Since ``tales:expressiontype`` is now in ``zope.browserpage``, update 605 conditional ZCML accordingly so it doesn't depend on the presence of 606 ``zope.app.pagetemplate`` anymore. 607 608 609 3.6.1 (2009-12-23) 610 ------------------ 611 612 - Ensure that our ``configure.zcml`` can be loaded without requiring further 613 dependencies. It uses a ``tales:expressiontype`` directive defined in 614 ``zope.app.pagetemplate.`` We keep that dependency optional, as not all 615 consumers of this package use ZCML to configure the expression type. 616 617 618 3.6.0 (2009-12-22) 619 ------------------ 620 621 - Updated test dependency to use ``zope.browserpage``. 622 623 624 3.5.0 (2009-03-18) 625 ------------------ 626 627 - Add very simple, but useful base class for implementing content 628 providers, see ``zope.contentprovider.provider.ContentProviderBase``. 629 630 - Remove unneeded testing dependencies. We only need ``zope.testing`` and 631 ``zope.app.pagetemplate``. 632 633 - Remove zcml slug and old zpkg-related files. 634 635 - Added setuptools dependency to setup.py. 636 637 - Clean up package's description and documentation a bit. Remove 638 duplicate text in README. 639 640 - Change mailing list address to zope-dev at zope.org instead of 641 retired one. 642 643 - Change ``cheeseshop`` to ``pypi`` in the package url. 644 645 646 3.4.0 (2007-10-02) 647 ------------------ 648 649 - Initial release independent of the main Zope tree. 650 651Keywords: zope3 content provider 652Platform: UNKNOWN 653Classifier: Development Status :: 5 - Production/Stable 654Classifier: Environment :: Web Environment 655Classifier: Intended Audience :: Developers 656Classifier: License :: OSI Approved :: Zope Public License 657Classifier: Programming Language :: Python 658Classifier: Natural Language :: English 659Classifier: Operating System :: OS Independent 660Classifier: Topic :: Internet :: WWW/HTTP 661Classifier: Framework :: Zope3 662