Django-esque URL Resolution in Nevow
Posted on March 09, 2007 by oubiwann

So, from the previous post on object publishing in Nevow, we had the following resources:
- http://localhost:8080/
- http://localhost:8080/m ystuff
- http://localhost:8080/yourstuff
It's actually fairly straight-forward. All we need to do is the following:
- Create a tuple of patterns.
- Override the locateChild() method in our "root" class.
urlPatterns = (Then, in SiteRoot, we could do something like the following:
(r'/mystuff(.*)', MyStuffResource),
(r'/yourstuff/blog(.)', BlogResource),
(r'/yourstuff(.)', YourStuffResource),
)
def locateChild(self, context, segments):What we're doing here is interrupting the "natural" flow of Nevow's path processing. If there are more segments once we've found a match, we pass the additional segments on to the child resource's locateChild() method. If not, we have a final destination and can return the resource itself.
path = '/'.join(('',) + segments)
for regex, resource in urlPatterns:
match = re.match(regex, path)
if match:
newPath = match.groups()[0]
r = resource()
if newPath in ['', '/']:
return r, ()
else:
newSegments = newPath.split('/')[1:]
return r.locateChild(context, newSegments)
return super(SiteRoot, self).locateChild(context, segments)
Here are some screenshots of this in action:




You can browse the code for this at the following links:
- The example as a single .tac file
- The same example, split up into separate files
Comments?
This blog doesn't use standard (embedded) comments; however, since
the site is hosted on Github, if there is
something you'd like to share, please do so by
opening a
"comment" ticket!