twistedその3
上位プロキシ。上位プロキシにはProxomitronを使った。
ソースは
http://lab.hde.co.jp/python/twisted/
で紹介されているものほぼそのままデス。
だいぶショートカットできました。感謝です。
from twisted.web import http, proxy from twisted.internet import reactor from twisted.python import log import urlparse PROXY_HOST='localhost' PROXY_PORT=8080 class UpperProxyRequest(proxy.ProxyRequest): def process(self): parsed = urlparse.urlparse(self.uri) protocol = parsed[0] host = parsed[1] print self.method port = self.ports[protocol] if ':' in host: host, port = host.split(':') port = int(port) rest = urlparse.urlunparse(('', '') + parsed[2:]) if not rest: rest = rest + '/' class_ = self.protocols[protocol] headers = self.getAllHeaders().copy() if 'host' not in headers: headers['host'] = host self.content.seek(0, 0) s = self.content.read() clientFactory = class_( self.method, self.uri, self.clientproto, headers, s, self) assert(PROXY_HOST) assert(PROXY_PORT) self.reactor.connectTCP(PROXY_HOST, PROXY_PORT, clientFactory) proxy.Proxy.requestFactory=UpperProxyRequest if __name__=="__main__": import sys log.startLogging(sys.stdout) f=http.HTTPFactory() f.protocol=proxy.Proxy reactor.listenTCP(10080, f) reactor.run()
+-------+ |reactor| +-------+---------+ +-----+ +-----------------+ +10080 HTTPFactory|->|Proxy|->|UpperProxyRequest| +-----------------+ +-----+ +----------------------------------+ A |process-> ProxyClientFactory| | +------------------V---------+------+ +-------+ |ProxyClient 上位Proxyから取ってくる| |browser| +-----------------------------------+ +-------+
ProxyClientが地味に優秀で直接でもProxy経由でもどっちでも取ってこれるようだ。