简体   繁体   中英

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

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

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" (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM