#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import tornado.gen
import tornado.ioloop
import tornado.web
import tornado.curl_httpclient
import tornado.httpclient
class ProxyHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
url = self.request.uri
print('request url: ', url)
request = tornado.httpclient.HTTPRequest(
url=url,
method=self.request.method,
body=self.request.body,
headers=self.request.headers,
allow_ipv6=True,
follow_redirects=True),
client = tornado.httpclient.AsyncHTTPClient()
response = yield tornado.gen.Task(client.fetch, request)
if response.error and not isinstance(response.error, tornado.httpclient.HTTPError):
self.write("Internal server error:\n" + str(response.error))
raise tornado.web.HTTPError(500)
else:
self.set_status(response.code)
for header in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
v = response.headers.get(header)
if v:
self.set_header(header, v)
if response.body:
self.write(response.body)
self.finish()
if __name__ == '__main__':
app = tornado.web.Application([
(r'.*', ProxyHandler),
], debug=True)
app.listen(8888)
tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
tornado.ioloop.IOLoop.instance().start()