3

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()

2 Answers 2

6

From https://www.safaribooksonline.com/library/view/twisted-network-programming/9781449326104/ch04.html :

The isLeaf instance variable describes whether or not a resource will have children. Without more work on our part..., only leaf resources get rendered

Example:

  • /index.html is a typical leaf
  • /users/ is not if there are endpoints like /users/joe
Sign up to request clarification or add additional context in comments.

1 Comment

This is a fairly complete answer. isLeaf is really as simple as stated above. It just means that there are no more branching resources off of the "isLeaf" resource. So basically if you're not going to render other resources from a particular resource, then set isLeaf to signify that.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.