Home >Backend Development >Python Tutorial >HTTP proxy server
Recently, I plan to study python socket programming in depth, so I plan to learn it and imitate it. I find that it is not easy to write well. Many problems arise in the middle. It is easy to see but difficult to do.
import socket import thread import urlparse import select BUFLEN=8192 class Proxy(object): def __init__(self,conn,addr): self.source=conn self.request="" self.headers={} self.destnation=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.run() def get_headers(self): header='' while True: header+=self.source.recv(BUFLEN) index=header.find('\n') if index >0: break #firstLine,self.request=header.split('\r\n',1) firstLine=header[:index] self.request=header[index+1:] self.headers['method'],self.headers['path'],self.headers['protocol']=firstLine.split() def conn_destnation(self): url=urlparse.urlparse(self.headers['path']) hostname=url[1] port="80" if hostname.find(':') >0: addr,port=hostname.split(':') else: addr=hostname port=int(port) ip=socket.gethostbyname(addr) print ip,port self.destnation.connect((ip,port)) data="%s %s %s\r\n" %(self.headers['method'],self.headers['path'],self.headers['protocol']) self.destnation.send(data+self.request) print data+self.request def renderto(self): readsocket=[self.destnation] while True: data='' (rlist,wlist,elist)=select.select(readsocket,[],[],3) if rlist: data=rlist[0].recv(BUFLEN) if len(data)>0: self.source.send(data) else: break def run(self): self.get_headers() self.conn_destnation() self.renderto() class Server(object): def __init__(self,host,port,handler=Proxy): self.host=host self.port=port self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind((host,port)) self.server.listen(5) self.handler=handler def start(self): while True: try: conn,addr=self.server.accept() thread.start_new_thread(self.handler,(conn,addr)) except: pass if __name__=='__main__': s=Server('127.0.0.1',8080) s.start() import socket import thread import urlparse import select BUFLEN=8192 class Proxy(object): def __init__(self,conn,addr): self.source=conn self.request="" self.headers={} self.destnation=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.run() def get_headers(self): header='' while True: header+=self.source.recv(BUFLEN) index=header.find('\n') if index >0: break #firstLine,self.request=header.split('\r\n',1) firstLine=header[:index] self.request=header[index+1:] self.headers['method'],self.headers['path'],self.headers['protocol']=firstLine.split() def conn_destnation(self): url=urlparse.urlparse(self.headers['path']) hostname=url[1] port="80" if hostname.find(':') >0: addr,port=hostname.split(':') else: addr=hostname port=int(port) ip=socket.gethostbyname(addr) print ip,port self.destnation.connect((ip,port)) data="%s %s %s\r\n" %(self.headers['method'],self.headers['path'],self.headers['protocol']) self.destnation.send(data+self.request) print data+self.request def renderto(self): readsocket=[self.destnation] while True: data='' (rlist,wlist,elist)=select.select(readsocket,[],[],3) if rlist: data=rlist[0].recv(BUFLEN) if len(data)>0: self.source.send(data) else: break def run(self): self.get_headers() self.conn_destnation() self.renderto() class Server(object): def __init__(self,host,port,handler=Proxy): self.host=host self.port=port self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind((host,port)) self.server.listen(5) self.handler=handler def start(self): while True: try: conn,addr=self.server.accept() thread.start_new_thread(self.handler,(conn,addr)) except: pass if __name__=='__main__': s=Server('127.0.0.1',8080) s.start()
In fact, Http The proxy server itself is not difficult, but it is quite troublesome to write. I will not go into the source code in detail here, it is very simple. Mainly talk about the problems I encountered.
1: I originally only knew that the first parameter of thread.start_new_thread is a function object, but when I saw the above blog post, I was stunned. This is okay, so I quickly tested it:
import thread class Hello: def __init__(self,content): print content def cs(): thread.start_new_thread(Hello, ("Hello World",)) if __name__=='__main__': cs() import thread class Hello: def __init__(self,content): print content def cs(): thread.start_new_thread(Hello, ("Hello World",)) if __name__=='__main__': cs()
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
How can a parameter be an object? I laughed and despised the author a little. So, I went to bed. The next day, I still didn’t give up, so I downloaded the code and tried it locally. It was ok. I immediately realized that it was me, so I immediately went to Baidu.
import thread class Hello: def __init__(self,content,lock): print content """ do something .... At the end,release the lock """ lock.release() def cs(): lock=thread.allocate_lock() lock.acquire() thread.start_new_thread(Hello, ("Hello World",lock)) while True: if not lock.locked(): break print "lock release" if __name__=='__main__': cs() import thread class Hello: def __init__(self,content,lock): print content """ do something .... At the end,release the lock """ lock.release() def cs(): lock=thread.allocate_lock() lock.acquire() thread.start_new_thread(Hello, ("Hello World",lock)) while True: if not lock.locked(): break print "lock release" if __name__=='__main__': cs()2. The second error is comparing 2self.source.send[data]peError: 'builtin_function_or_method' object is unsubscriptable self.source.send[data]TypeError : 'builtin_function_or_method' object is unsubscriptableThe main meaning is that built-in functions or methods cannot have subscripts, you know