Object Traversal ================ **Object traversal** is the process Nevow uses to determine what object to use to render HTML for a particular URL. When an HTTP request comes in to the web server, the object publisher splits the URL into segments, and repeatedly calls methods which consume path segments and return objects which represent that path, until all segments have been consumed. At the core, the Nevow traversal API is very simple. However, it provides some higher level functionality layered on top of this to satisfy common use cases. Object Traversal Basics ----------------------- The **root resource** is the top-level object in the URL space; it conceptually represents the URI ``/`` . The Nevow **object traversal** and **object publishing** machinery uses only two methods to locate an object suitable for publishing and to generate the HTML from it; these methods are described in the interface ``nevow.inevow.IResource`` : :: class IResource(Interface): def locateChild(self, ctx, segments): """Locate another object which can be adapted to IResource Return a tuple of resource, path segments """ def renderHTTP(self, ctx): """Render a request """ ``renderHTTP`` can be as simple as a method which simply returns a string of HTML. Let's examine what happens when object traversal occurs over a very simple root resource: :: from zope.interface import implements class SimpleRoot(object): implements(inevow.IResource) def locateChild(self, ctx, segments): return self, () def renderHTTP(self, ctx): return "Hello, world!" This resource, when passed as the root resource to ``appserver.NevowSite`` or ``wsgi.createWSGIApplication`` , will immediately return itself, consuming all path segments. This means that for every URI a user visits on a web server which is serving this root resource, the text ``"Hello, world!"`` will be rendered. Let's examine the value of ``segments`` for various values of URI: - ``/`` - ``('',)`` - ``/foo/bar`` - ``('foo', 'bar')`` - ``/foo/bar/baz.html`` - ``('foo', 'bar', 'baz.html')`` - ``/foo/bar/directory/`` - ``('foo', 'bar', 'directory', '')`` So we see that Nevow does nothing more than split the URI on the string ``/`` and pass these path segments to our application for consumption. Armed with these two methods alone, we already have enough information to write applications which service any form of URL imaginable in any way we wish. However, there are some common URL handling patterns which Nevow provides higher level support for. ``locateChild`` In Depth ------------------------- One common URL handling pattern involves parents which only know about their direct children. For example, a ``Directory`` object may only know about the contents of a single directory, but if it contains other directories, it does not know about the contents of them. Let's examine a simple ``Directory`` object which can provide directory listings and serves up objects for child directories and files: :: from zope.interface import implements class Directory(object): implements(inevow.IResource) def __init__(self, directory): self.directory = directory def renderHTTP(self, ctx): html = ['') return ''.join(html) def locateChild(self, ctx, segments): name = segments[0] fullpath = os.path.join(self.directory, name) if not os.path.exists(fullpath): return None, () # 404 if os.path.isdir(fullpath): return Directory(fullpath), segments[1:] if os.path.isfile(fullpath): return static.File(fullpath), segments[1:] Because this implementation of ``locateChild`` only consumed one segment and returned the rest of them (``segments[1:]`` ), the object traversal process will continue by calling ``locateChild`` on the returned resource and passing the partially-consumed segments. In this way, a directory structure of any depth can be traversed, and directory listings or file contents can be rendered for any existing directories and files. So, let us examine what happens when the URI ``"/foo/bar/baz.html"`` is traversed, where ``"foo"`` and ``"bar"`` are directories, and ``"baz.html"`` is a file. #. ``Directory('/').locateChild(ctx, ('foo', 'bar', 'baz.html'))`` returns ``Directory('/foo'), ('bar', 'baz.html')`` #. ``Directory('/foo').locateChild(ctx, ('bar', 'baz.html'))`` returns ``Directory('/foo/bar'), ('baz.html, )`` #. ``Directory('/foo/bar').locateChild(ctx, ('baz.html'))`` returns ``File('/foo/bar/baz.html'), ()`` #. No more segments to be consumed; ``File('/foo/bar/baz.html').renderHTTP(ctx)`` is called, and the result is sent to the browser. ``childFactory`` Method ------------------------ Consuming one URI segment at a time by checking to see if a requested resource exists and returning a new object is a very common pattern. Nevow's default implementation of ``IResource`` , ``nevow.rend.Page`` , contains an implementation of ``locateChild`` which provides more convenient hooks for implementing object traversal. One of these hooks is ``childFactory`` . Let us imagine for the sake of example that we wished to render a tree of dictionaries. Our data structure might look something like this: :: tree = dict( one=dict( foo=None, bar=None), two=dict( baz=dict( quux=None))) Given this data structure, the valid URIs would be: - / - /one - /one/foo - /one/bar - /two - /two/baz - /two/baz/quux Let us construct a ``rend.Page`` subclass which uses the default ``locateChild`` implementation and overrides the ``childFactory`` hook instead: :: class DictTree(rend.Page): def __init__(self, dataDict): self.dataDict = dataDict def renderHTTP(self, ctx): if self.dataDict is None: return "Leaf" html = ['') return ''.join(html) def childFactory(self, ctx, name): if name not in self.dataDict: return rend.NotFound # 404 return DictTree(self.dataDict[name]) As you can see, the ``childFactory`` implementation is considerably shorter than the equivalent ``locateChild`` implementation would have been. ``child_*`` methods and attributes ----------------------------------- Often we may wish to have some hardcoded URLs which are not dynamically generated based on some data structure. For example, we might have an application which uses an external CSS stylesheet, an external JavaScript file, and a folder full of images. The ``rend.Page.locateChild`` implementation provides a convenient way for us to express these relationships by using child-prefixed methods: :: class Linker(rend.Page): def renderHTTP(self, ctx): return """