spacepaste

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/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()