如何使我简单的扭曲代理工作?


问题内容

我正在尝试使用Twisted.Web框架。

请注意三行注释(#line1,#line2,#line3)。我想创建一个代理(网关?),该代理将根据URL将请求转发到两个服务器之一。如果我取消注释1或2的注释(其余注释),则该请求将被代理到正确的服务器。但是,当然,它不会基于URL选择服务器。

from twisted.internet import reactor
from twisted.web import proxy, server
from twisted.web.resource import Resource

class Simple(Resource):
    isLeaf = True
    allowedMethods = ("GET","POST")

    def getChild(self, name, request):
        if name == "/" or name == "":
            return proxy.ReverseProxyResource('localhost', 8086, '')
        else:
            return proxy.ReverseProxyResource('localhost', 8085, '')

simple = Simple()
# site = server.Site(proxy.ReverseProxyResource('localhost', 8085, '')) #line1   
# site = server.Site(proxy.ReverseProxyResource('localhost', 8085, '')) #line2   
site = server.Site(simple)                                              #line3   
reactor.listenTCP(8080, site)
reactor.run()

如上面的代码所示,当我运行此脚本并导航到服务器“ localhost:8080 / ANYTHING_AT_ALL”时,得到以下响应。

不允许的方法

您的浏览器通过“ GET”方法与我联系(在/ ANYTHING_AT_ALL)。我只在这里允许GET,POST方法。

我不知道我在做什么错?任何帮助,将不胜感激。


问题答案:

由于您的Simple类实现了该getChild()方法,因此暗示这不是叶节点,但是您可以通过设置声明它是叶节点isLeaf = True。(叶节点如何生子?)。

尝试更改isLeaf = TrueisLeaf = False,您会发现它会按预期重定向到代理。

Resource.getChild文档字符串:

... This will not be called if the class-level variable 'isLeaf' is set in
    your subclass; instead, the 'postpath' attribute of the request will be
    left as a list of the remaining path elements....