[英]Python - Twisted, Proxy and modifying content
所以我查看了一些涉及使用python和Twisted框架編寫HTTP代理的事情。
基本上,像其他一些問題一樣,我希望能夠修改將被發送回瀏覽器的數據。 也就是說,瀏覽器請求資源,代理將獲取它。 在資源返回瀏覽器之前,我希望能夠修改任何(HTTP標頭和內容)內容。
這個( 需要幫助寫一個扭曲的代理 )是我最初找到的。 我試了一下,但它對我不起作用。 我也發現了這個( Python Twisted代理 - 如何攔截數據包 ),我認為它可以工作,但我只能看到來自瀏覽器的HTTP請求。
我正在尋找任何建議。 我有一些想法是使用ProxyClient和ProxyRequest類並覆蓋函數,但我讀到Proxy類本身是兩者的組合。
對於那些可能要求查看一些代碼的人,應該注意的是我只使用了上面兩個例子。 任何幫助都很棒。
謝謝。
要創建可以修改服務器響應頭的ProxyFactory
,您可以覆蓋ProxyClient.handle*()
方法的內容 :
from twisted.python import log
from twisted.web import http, proxy
class 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 = ProxyClient
class ProxyRequest(proxy.ProxyRequest):
protocols = dict(http=ProxyClientFactory)
class Proxy(proxy.Proxy):
requestFactory = ProxyRequest
class ProxyFactory(http.HTTPFactory):
protocol = Proxy
我通過查看twisted.web.proxy
的來源獲得了這個解決方案。 我不知道它是多么慣用。
要將其作為腳本或通過twistd
,請在末尾添加:
portstr = "tcp:8080:interface=localhost" # serve on localhost:8080
if __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
對於使用twisted
的雙向代理,請參閱文章:
http://sujitpal.blogspot.com/2010/03/http-debug-proxy-with-twisted.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.