标签 tornado 下的文章

tornado实现http代理


#!/bin/env python
#-*- coding:utf-8 -*-
#code by Mosuan
#Email: 934817794@qq.com
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import gen
import tornado.httpclient
import tornado.concurrent
import tornado.ioloop
import tornado.autoreload
import time
from tornado.options import define, options

#代理端口
define("port", default=8000, help="run on the given port", type=int)
#设置DEBUG模式
settings = {'debug' : True}
define("debug",default=True,help="Debug",type=bool)
class SleepHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        return self.get()
        
    @tornado.web.asynchronous
    def get(self):

        def handle_request(response):
            '''
            回调发包返回页面内容
            '''
            if response.error:
                print "Error:", response.error
            else:
                self.write(response.body)
                self.finish()

        body = self.request.body
        #不一定是POST请求的
        if not body:
            body = None

        #发包
        raq = tornado.httpclient.HTTPRequest(
            url=self.request.uri,
            method=self.request.method,
            body=body,
            headers=self.request.headers,
            follow_redirects=False,
            allow_nonstandard_methods=True)
        #回调
        tornado.httpclient.AsyncHTTPClient().fetch(raq,handle_request)


if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[
            (r".*", SleepHandler)
            ],debug=True)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()