栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-扭曲,代理和修改内容

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python-扭曲,代理和修改内容

要创建

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610501.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号