O'Reilly logo

Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft, Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.14. Rendering Arbitrary Objects with Nevow

Credit: Valentino Volonghi, Matt Goodall

Problem

You're writing a web application that uses the Twisted networking framework and the Nevow subsystem for web rendering. You need to be able to render some arbitrary Python objects to a web page.

Solution

Interfaces and adapters are the Twisted and Nevow approach to this task. Here is a toy example web server script to show how they work:

from twisted.application import internet, service from nevow import appserver, compy, inevow, loaders, rend from nevow import tags as T # Define some simple classes to be the example's "application data" class Person(object): def _ _init_ _(self, firstName, lastName, nickname): self.firstName = firstName self.lastName = lastName self.nickname = nickname class Bookmark(object): def _ _init_ _(self, name, url): self.name = name self.url = url # Adapter subclasses are the right way to join application data to the web: class PersonView(compy.Adapter): """ Render a full view of a Person. """ _ _implements_ _ = inevow.IRenderer attrs = 'firstName', 'lastName', 'nickname' def rend(self, data): return T.div(_class="View person") [ T.p['Person'], T.dl[ [(T.dt[attr], T.dd[getattr(self.original, attr)]) for attr in self.attrs] ] ] class BookmarkView(compy.Adapter): """ Render a full view of a Bookmark. """ _ _implements_ _ = inevow.IRenderer attrs = 'name', 'url' def rend(self, data): return T.div(_class="View bookmark") [ T.p['Bookmark'], T.dl[ [(T.dt[attr], T.dd[getattr(self.original, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required