在扭曲的代理中连接请求和响应

时间:2013-07-15 00:10:06

标签: python proxy twisted twisted.web

我正在尝试使用Twisted Framework的代理记录请求和响应以及两者的标头。

现在,请求由process类中的HTTPProxyRequest方法处理,响应在HTTPProxyClient处理。

我想知道哪个响应对应哪个请求。 这样做的最不具破坏性的方法是什么?

from twisted.python import log
from twisted.web import http
from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient



class HTTPProxyClient(ProxyClient):
    def __init__(self, command, rest, version, headers, data, father):
        ProxyClient.__init__(self, command, rest, version, headers, data, father)
        self.new_buffer = ""
        self.new_headers = {}
    def handleHeader(self, key, value):
        self.new_headers[key] = value
        ProxyClient.handleHeader(self, key, value)

    def handleResponsePart(self, buffer):
        # log.msg("RESPONSE_CONTENT: %s" % buffer)
        ProxyClient.handleResponsePart(self, buffer)
        self.new_buffer += buffer

    def handleResponseEnd(self):
        log.msg("RESPONSE_HEADERS:%s \n RESPONSE_CONTENT: %s" % (str(self.new_headers),self.new_buffer))
        ProxyClient.handleResponseEnd(self)

class HTTPProxyFactory(ProxyClientFactory):
    protocol = HTTPProxyClient

class HTTPProxyRequest(ProxyRequest):
    protocols = {'http' : HTTPProxyFactory}

    def process(self):
        log.msg("REQUEST_METHOD:", self.method)
        # log.msg(self.content.read())
        for k,v in self.requestHeaders.getAllRawHeaders():
            # log.msg("REQUEST_HEADER: %s : %s" % (k,v))
            pass
        # log.msg("\n \n")
        if self.method == "POST":
            log.msg("LOGGING POST CONTENT:", self.content.read())

        ProxyRequest.process(self)

class HTTPProxy(Proxy):

    requestFactory = HTTPProxyRequest


if __name__ == '__main__': # $ python proxy_modify_request.py
    import sys
    from twisted.internet import reactor
    log.startLogging(sys.stdout)
    factory = http.HTTPFactory()
    factory.protocol = HTTPProxy

    reactor.listenTCP(8070, factory)
    reactor.run()

0 个答案:

没有答案