Search code examples
pythontwistedtwisted.internet

What is the purpose of Twisted's isLeaf attribute?


I found the following example of a Twisted request handler. I'm not clear what the isLeaf attribute is for. Why should I set it on a resource?

from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource

class RequestHandler(Resource):
    isLeaf = True

    def render_GET(self, request):
        request.setResponseCode(200)
        return "HelloWorld"

if __name__ == '__main__':
    resource = RequestHandler()
    factory = Site(resource)
    reactor.listenTCP(8001, factory)
    reactor.run()

Solution

  • See twisted.web.resource.IResource.isLeaf documentation --

    Signal if this IResource implementor is a "leaf node" or not. If True, getChildWithDefault will not be called on this Resource.

    The way Twisted finds a resource to render is by splitting the path into segments, and calling "getChildWithDefault" on the root, and then whatever the root returns and so on. It stops if it either runs out of segments, or a "leaf" (i.e., isLeaf=True) resource is found.

    At that point, it will call the render method on the resource. In a leaf resource, the renderer will often want to look at the "request.postpath" attribute -- stashed there is the list of segments that have not been used up to find the resource.