2010-02-15 21 views
3

我正在嘗試使用Twisted.Web框架。如何讓我的簡單雙絞線代理工作?

注意下列三個行註釋(#一號線,2號線#,#3號線)。我想創建一個代理(網關?),根據網址將請求轉發給兩個服務器之一。如果我取消註釋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() 

正如上面的代碼目前維持,當我運行此腳本並導航到服務器的「本地主機:8080/ANYTHING_AT_ALL」我得到的迴應如下。

不允許的方法

您的瀏覽器找我(在/ ANYTHING_AT_ALL)與方法 「GET」。我在 只允許GET,POST這裏的方法。

我不知道我做錯了什麼?任何幫助,將不勝感激。

回答

4

由於您的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.... 
+0

感謝您的回覆。是的,我顯然沒有讀足夠批判的眼光。似乎我在「葉子」上,因爲我的路徑只有1的深度,但我想我應該想到「如果我是葉子,我怎麼能生一個孩子」。謝謝。 – 2010-02-16 20:47:31

2

下面是最終的工作方案。基本上兩個資源請求轉到GAE服務器,剩下的所有請求都轉到GWT服務器。

除了實施mhawke的變化,只有一個其他的變化,那就是將「‘/’+姓名」到代理服務器的路徑。我認爲這是必須完成的,因爲這部分路徑被消耗並放置在'名稱'變量中。

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

謝謝。