【问题标题】:How do I get my simple twisted proxy to work?如何让我的简单扭曲代理工作?
【发布时间】:2011-01-17 04:24:06
【问题描述】:

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

注意三行 cmets(#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 方法。

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

【问题讨论】:

    标签: python proxy twisted


    【解决方案1】:

    这是最终的工作解决方案。基本上有两个资源请求到 GAE 服务器,剩下的所有请求都到 GWT 服务器。

    除了实现 mhawke 的更改之外,只有另一个更改,那就是在代理服务器路径中添加 '"/" + name'。我认为必须这样做,因为路径的那部分已被消耗并放置在“名称”变量中。

    from twisted.internet import reactor
    from twisted.web import proxy, server
    from twisted.web.resource import Resource
    
    class Simple(Resource):
        isLeaf = False
        allowedMethods = ("GET","POST")
        def getChild(self, name, request):
            print "getChild called with name:'%s'" % name
            if name == "get.json" or name == "post.json":
                print "proxy on GAE"
                return proxy.ReverseProxyResource('localhost', 8085, "/"+name)
            else:
                print "proxy on GWT"
                return proxy.ReverseProxyResource('localhost', 8086, "/"+name)
    
    simple = Simple()
    site = server.Site(simple)
    reactor.listenTCP(8080, site)
    reactor.run()
    

    谢谢。

    【讨论】:

      【解决方案2】:

      由于您的Simple 类实现了getChild() 方法,因此暗示这不是叶节点,但是,您通过设置isLeaf = True 来声明它是叶节点。 (叶节点怎么可能有孩子?)。

      尝试将isLeaf = True 更改为isLeaf = 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....
      

      【讨论】:

      • 感谢您的回复。是的,我显然没有用足够批判的眼光阅读。似乎我在“叶子”上,因为我的路径只有 1 的深度,但我想我应该想到“如果我是叶子,我怎么能生孩子”。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2013-02-05
      • 1970-01-01
      相关资源
      最近更新 更多