摘要

强烈建议阅读中文版的入门教程:http://www.tornadoweb.cn/documentation


示例1

代理百度:

import signal

from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application
from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient

class MainRequestHandler(RequestHandler):
    @coroutine
    def get(self):
        httpclient = AsyncHTTPClient()
        response = yield httpclient.fetch("http://www.baidu.com/")
        if response.error:
            self.set_header("Content-Type", "text/plain")
            self.write("error accurs:%s" % response)
            return

        self.set_status(response.code)
        for hn, hv in response.headers.iteritems():
            if hn == "Transfer-Encoding":
                continue
            self.set_header(hn, hv)
        self.write(response.body)

def handle_signal():
    def on_quit(sn, fo):
        print("stoping IOLoop")
        IOLoop.current().stop()
    signal.signal(signal.SIGINT, on_quit)

def main():
    handle_signal()

    app = Application([
        (r"/*", MainRequestHandler)
    ])
    app.listen(8081)
    IOLoop.current().start()

if __name__ == "__main__":
    main()