Skip to content Skip to sidebar Skip to footer

Need Help Writing A Twisted Proxy

I want to write a simple proxy that shuffles the text in the body of the requested pages. I have read parts of the twisted documentation and some other similar questions here on st

Solution 1:

What I do is to implement a new ProxyClient, where I modify the data after I've downloaded it from the webserver, and before I send it off to the web browser.

from twisted.web import proxy, http
classMyProxyClient(proxy.ProxyClient):
 def__init__(self,*args,**kwargs):
  self.buffer = ""
  proxy.ProxyClient.__init__(self,*args,**kwargs)
 defhandleResponsePart(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
 defhandleResponseEnd(self):
  ifnot 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)

classMyProxyClientFactory(proxy.ProxyClientFactory):
 protocol = MyProxyClient

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

classMyProxy(http.HTTPChannel):
 requestFactory = ProxyRequest

classProxyFactory(http.HTTPFactory):
 protocol = MyProxy

Hope this also works for you.

Post a Comment for "Need Help Writing A Twisted Proxy"