使用python实现反向代理

^_^的我 1月前 ⋅ 244 阅读

使用的python版本:Python 3.8.2

1.pip版本:20.1
2.实现代码如下:
```python
	from http.server import HTTPServer, BaseHTTPRequestHandler
    import hashlib
    import os
    import urllib.request as urllib2
    import urllib

    class CacheHandler(BaseHTTPRequestHandler):
        def do_GET(self):
          m = hashlib.md5()
          m.update(self.path.encode("UTF8"))
          cache_filename = m.hexdigest()
          if os.path.exists(cache_filename):
              print("Cache hit")
              data = open(cache_filename, 'r', -1 ).readlines()
          else:
              print("Cache miss")
              print("http://www.host.com" + self.path)
              data = urllib2.urlopen("http://www.host.com" + self.path).readlines()
              open(cache_filename, 'wb', -1).writelines(data)
              self.send_response(200)
              self.end_headers()
              self.wfile.writelines(data)
    def run():
        server_address = ('', 8000)
        httpd = HTTPServer(server_address, CacheHandler)
        httpd.serve_forever()

    if __name__ == '__main__':
        run()
```

ptyhon2.x版本实现代码:

```python
import BaseHTTPServer
import hashlib
import os
import urllib2

class CacheHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
      m = hashlib.md5()
      m.update(self.path)
      cache_filename = m.hexdigest()
      if os.path.exists(cache_filename):
          print "Cache hit"
          data = open(cache_filename).readlines()
      else:
          print "Cache miss"
          data = urllib2.urlopen("http://targetserver" + self.path).readlines()
          open(cache_filename, 'wb').writelines(data)
      self.send_response(200)
      self.end_headers()
      self.wfile.writelines(data)

def run():
    server_address = ('', 8000)
    httpd = BaseHTTPServer.HTTPServer(server_address, CacheHandler)
    httpd.serve_forever()

if __name__ == '__main__':
    run()
```

全部评论: 0

    我有话说: