2011-06-27 26 views
9

リクエストされたページの本文にテキストをシャッフルする簡単なプロキシを書きたいと思っています。私はねじれたドキュメントの一部と他の同様の質問をここstackoverflowで読んだことがありますが、私はまだnoobのビットですので、まだ得られません。ツイストプロキシ作成の手助けが必要

これは私が今持っているもの、私はあなたが私を助けてくださいすることができ

from twisted.web import proxy, http 
from twisted.internet import protocol, reactor 
from twisted.python import log 
import sys 

log.startLogging(sys.stdout) 

class ProxyProtocol(http.HTTPChannel): 
    requestFactory = PageHandler 

class ProxyFactory(http.HTTPFactory): 
    protocol = ProxyProtocol 

if __name__ == '__main__': 
    reactor.listenTCP(8080, ProxyFactory()) 
    reactor.run() 

ページにアクセスして変更する方法がわからないのですか?簡単な例がわかります(例:身体に何かを追加するなど)。

答えて

6

私は、新しいProxyClientを実装します。ここでは、Webサーバーからダウンロードした後、Webブラウザに送信する前にデータを変更します。

from twisted.web import proxy, http 
class MyProxyClient(proxy.ProxyClient): 
def __init__(self,*args,**kwargs): 
    self.buffer = "" 
    proxy.ProxyClient.__init__(self,*args,**kwargs) 
def handleResponsePart(self, buffer): 
    # Here you will get the data retrieved from the web server 
    # In this example, we will buffer the page while we shuffle it. 
    self.buffer = buffer + self.buffer 
def handleResponseEnd(self): 
    if not self._finished: 
    # We might have increased or decreased the page size. Since we have not written 
    # to the client yet, we can still modify the headers. 
    self.father.responseHeaders.setRawHeaders("content-length", [len(self.buffer)]) 
    self.father.write(self.buffer) 
    proxy.ProxyClient.handleResponseEnd(self) 

class MyProxyClientFactory(proxy.ProxyClientFactory): 
protocol = MyProxyClient 

class ProxyRequest(proxy.ProxyRequest): 
protocols = {'http': MyProxyClientFactory} 
ports = {'http': 80 } 
def process(self): 
    proxy.ProxyRequest.process(self) 

class MyProxy(http.HTTPChannel): 
requestFactory = ProxyRequest 

class ProxyFactory(http.HTTPFactory): 
protocol = MyProxy 

これはあなたのためにもうまくいきます。

+0

私のプロキシ要求が404エラー応答を受け取ると、「遅延:失敗:twisted.web.error.Error:404が見つかりません」というエラーが表示されます。このエラーをどのように捕捉するのですか? –

関連する問題