Python基于BaseHTTPRequestHandler的HTTP代理V1.0

来源:互联网 发布:2016淘宝刷流量 编辑:程序博客网 时间:2024/06/10 11:49

proxyHandler.py

#coding=utf8from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServerimport socketimport urllibfrom zipdeal import GzipClassclass proxyHandler(BaseHTTPRequestHandler):    def do_POST(self):        #服务响应的链接uri        #类似http://xdcs-collector.ximalaya.com/api/v1/statistics        uri = self.path        #根据协议把url分成两部分,一部分是协议,例如http;        #另一部分是服务和接口:xdcs-collector.ximalaya.com/api/v1/statistics        #把另一部分内容放入到:   hostAndInterface             hostAndInterface = urllib.splittype(uri)[-1]        #根据服务器拆分成两个部分,一部分是服务器:xdcs-collector.ximalaya.com        #另一部分是接口:/api/v1/statistics        host, interface = urllib.splithost(hostAndInterface)        #根据/拆分成几个部分,获取最后一个元素的值,例如:statistics        lastOfInterface=interface.split("/")[-1]                #判断接口最后一个字符是否是:statistics,如果是则执行if之后的语句        if lastOfInterface=='statistics':                         #根据端口号拆分成两个部分:host、port               host, port = urllib.splitnport(host)                        #如果端口号小于80,把端口号设置为80            if port < 0:                port = 80                        #把服务域名转换为服务IP            host_ip = socket.gethostbyname(host)                        #从headers中删除headers['Proxy-Connection']的引用            # 然后把headers['Connection']设置为'keep-alive'            del self.headers['Proxy-Connection']            self.headers['Connection'] = 'keep-alive'                    #请求的第一行,把该行数据赋值给send_data变量            #requestline的格式如:POST http://xdcs-collector.ximalaya.com/api/v1/statistics HTTP/1.1            send_data = self.requestline                        #重新创建个head用来保存新的heads值            head = ''            for key, val in self.headers.items():                head = head + "%s: %s\r\n" % (key, val)                           #给请求的数据加上head和请求参数            send_data = send_data + head+'\r\n'                        #创建一个客户端套接字链接            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)            #客户端发送连接请求            client.connect((host_ip, port))            #客户端发送请求数据            client.sendall(send_data)                        #保存服务端返回的字段            data = ''            while True:                #把客户端从服务中接收的数据保存到一个临时变量tmp中                tmp = client.recv(8192)                #判断接收的数据是否为空,如果为空跳出循环                if not tmp:                    break                #不为空,把tmp中的数据传递给data                data = data + tmp                #断开链接            client.close()                         #把接收到的数据data写入到文件wfile中              self.wfile.write(data)                        #self.rfile存放的是请求数据而且数据还被gzip            #通过print打印到屏幕的都是乱码            GzipClass().GZFile(self.rfile.read())        else:            pass    #do_CONNECT = do_POST    #do_GET=do_POST    def test():    host='192.168.62.33'    port=8888    try:        server = HTTPServer((host, port), proxyHandler)        print 'Welcome to the Server HTTP On %s  Port %d...' %(host,port)        server.serve_forever()    except KeyboardInterrupt:        print '^C received, shutting down server'        server.socket.close()if __name__ == '__main__':    test()        

zipdeal.py

#coding=utf8import osimport gzip'''创建一个全局变量FILE_PATH并给变量赋值:gz文件所在路径'''class GzipClass():    def __init__(self):        self.FILE_PATH = 'D:\\DataProxy\\Pro_2.0\\GZfile\\request.gz'        #读取gz文件中的内容    def read_file(self,path):        try:            #判断路径是否存在,如果存在打开gz文件并读取            #不存在给出相应的提示信息            if os.path.exists(path):                with gzip.open(path, 'rb') as pf:                    return pf.read()            else:                print 'the path % is not exist!' %(path)        finally:            pf.close()                #把内容写入gz文件    def write_file(self,path, content):        try:            #判断路径是否存在,如果存在打开gz文件并读取            #不存在给出相应的提示信息            if os.path.exists(path):                with gzip.open(path, 'wb') as f:                    f.write(content)            else:                print 'the path % is not exist!' %(path)        finally:            f.close()                      def GZFile(self,content):        self.write_file(self.FILE_PATH, content)        con =self.read_file(self.FILE_PATH)        print '#' * 50        print con    if __name__ == '__main__':    GzipClass().GZFile("hellO")


0 0