我不是python twisted方面的专家,请帮我解决问题,
当我尝试路径localhost:8888/dynamicchild时,getchild没有调用。
甚至在我的资源中把isleaf设为false。
根据我的理解,当我尝试localhost:8888时,它应该会返回蓝色页面,当然它正在发生,但当我尝试localhost:8888/somex时,应该在屏幕上打印语句print“getchild called”,但现在它没有发生

from twisted.web import resource

from twisted.web import server
from twisted.internet import reactor

class MyResource(resource.Resource):
    isLeaf=False
    def render(self,req):
        return "<body bgcolor='#00aacc' />"

    def getChild(self,path,request):
        print " getChild called "


r=resource.Resource()
r.putChild('',MyResource())
f=server.Site(r)
reactor.listenTCP(8888,f)
reactor.run()

最佳答案

这是因为它是发送给服务器的根资源。站点构造函数的getChild方法被调用。
试试这样的方法:

from twisted.web import resource

from twisted.web import server
from twisted.internet import reactor

class MyResource(resource.Resource):
    isLeaf=False

    def __init__(self, color='blue'):
        resource.Resource.__init__(self)
        self.color = color

    def render(self,req):
        return "<body bgcolor='%s' />" % self.color

    def getChild(self,path,request):
        return MyResource('blue' if path == '' else 'red')

f=server.Site(MyResource())
reactor.listenTCP(8888,f)
reactor.run()

请求“/”现在将返回蓝色背景,其他所有内容返回“红色”。

10-06 15:28