【问题标题】:Need help writing a twisted proxy需要帮助编写一个扭曲的代理
【发布时间】:2011-09-23 10:21:01
【问题描述】:

我想编写一个简单的代理来随机播放请求页面正文中的文本。我已经阅读了有关 stackoverflow 的部分扭曲文档和其他一些类似问题,但我有点菜鸟,所以我仍然不明白。

这是我现在的,不知道怎么访问和修改页面

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

你能帮帮我吗?我会很感激一个简单的例子(例如,在正文中添加一些东西等......)。

【问题讨论】:

    标签: python proxy twisted


    【解决方案1】:

    我要做的是实现一个新的 ProxyClient,在我从网络服务器下载数据之后,在将数据发送到网络浏览器之前,我会在其中修改数据。

    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
    

    希望这也对你有用。

    【讨论】:

    • 当我的代理请求收到 404 错误响应时,我收到“Deferred 中未处理的错误:Failure: twisted.web.error.Error: 404 Not Found”。我如何发现这个错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多