Twisted 中资源的 getChild 不被调用

1 投票
1 回答
1207 浏览
提问于 2025-04-17 15:13

我对Python的Twisted库不是很精通,希望能帮我解决一个问题。 当我尝试访问路径 localhost:8888/dynamicchild 时,getChild这个方法没有被调用。即使我在我的资源里把isLeaf设置为False。

根据我的理解,当我访问 localhost:8888 时,应该会返回一个蓝色的页面,这个是正常的。但是每当我尝试访问 localhost:8888/somex 时,应该在屏幕上打印出“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()

1 个回答

2

这是因为你发送到服务器的是根资源,也就是 Site 构造函数中的 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()

现在请求 '/' 会返回蓝色背景,而其他请求则会返回红色。

撰写回答