要创建
ProxyFactory可以修改服务器响应头的内容,您可以覆盖
ProxyClient.handle*()方法:
from twisted.python import logfrom twisted.web import http, proxyclass ProxyClient(proxy.ProxyClient): """Mangle returned header, content here. Use `self.father` methods to modify request directly. """ def handleHeader(self, key, value): # change response header here log.msg("Header: %s: %s" % (key, value)) proxy.ProxyClient.handleHeader(self, key, value) def handleResponsePart(self, buffer): # change response part here log.msg("Content: %s" % (buffer[:50],)) # make all content upper case proxy.ProxyClient.handleResponsePart(self, buffer.upper())class ProxyClientFactory(proxy.ProxyClientFactory): protocol = ProxyClientclass ProxyRequest(proxy.ProxyRequest): protocols = dict(http=ProxyClientFactory)class Proxy(proxy.Proxy): requestFactory = ProxyRequestclass ProxyFactory(http.HTTPFactory): protocol = Proxy通过查看的来源,可以得到此解决方案
twisted.web.proxy。我不知道这是多么习惯。
要将其作为脚本或通过运行
twistd,请在末尾添加:
portstr = "tcp:8080:interface=localhost" # serve on localhost:8080if __name__ == '__main__': # $ python proxy_modify_request.py import sys from twisted.internet import endpoints, reactor def shutdown(reason, reactor, stopping=[]): """Stop the reactor.""" if stopping: return stopping.append(True) if reason: log.msg(reason.value) reactor.callWhenRunning(reactor.stop) log.startLogging(sys.stdout) endpoint = endpoints.serverFromString(reactor, portstr) d = endpoint.listen(ProxyFactory()) d.addErrback(shutdown, reactor) reactor.run()else: # $ twistd -ny proxy_modify_request.py from twisted.application import service, strports application = service.Application("proxy_modify_request") strports.service(portstr, ProxyFactory()).setServiceParent(application)用法
$ twistd -ny proxy_modify_request.py
在另一个终端:
$ curl -x localhost:8080 http://example.com



