SimpleHTTPProxy.py 995 B

1234567891011121314151617181920212223242526272829303132
  1. import urllib2
  2. import BaseHTTPServer, SimpleHTTPServer
  3. class SimpleHTTPProxy(SimpleHTTPServer.SimpleHTTPRequestHandler, object):
  4. proxy_routes = {}
  5. @classmethod
  6. def set_routes(cls, proxy_routes):
  7. cls.proxy_routes = proxy_routes
  8. def do_GET(self):
  9. parts = self.path.split('/')
  10. if len(parts) >= 2 and parts[1] in self.proxy_routes:
  11. url = self.proxy_routes[parts[1]] + '/'.join(parts[2:])
  12. self.porxy_request(url)
  13. else:
  14. super(SimpleHTTPProxy, self).do_GET()
  15. def porxy_request(self, url):
  16. try:
  17. print url
  18. response = urllib2.urlopen(url)
  19. except urllib2.HTTPError as e:
  20. self.send_response(e.code)
  21. self.end_headers()
  22. return
  23. self.send_response(response.getcode())
  24. for name, value in response.headers.items():
  25. self.send_header(name, value)
  26. self.end_headers()
  27. self.copyfile(response, self.wfile)