tornado實現(xiàn)異步請求

from tornado.web import FallbackHandler, RequestHandler, Application, asynchronous
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.escape import json_encode, json_decode
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPClient
import functools
from flask import Flask


app = Flask(__name__)
class TorTest(RequestHandler):

    def write(self, truck):
        RequestHandler.write(self, truck)


    @asynchronous
    def post(self):
        ptlogin_url = "http://127.0.0.1:5000/hello"
        pt_body = json_encode({
                "appid": 'abcdefg',
                "sthirdparty": channel,
                "sid": sid,
                })
        
        http_client = AsyncHTTPClient()
        request = HTTPRequest(ptlogin_url, 
                              method="POST", 
                              headers={'Content-Type': 'text/plain', 'Content-Length': len(pt_body)},
                              body=pt_body
                              )
        
        http_client.fetch(request, functools.partial(self.on_ptlogin, pt_body))
        print 'post'
        self.finish()

    def on_ptlogin(self, pt_body, responseorg):
        
        self.write(pt_body)
        self.finish()
        return


@app.route('/hello', methods=['GET','POST'])
def hello():
    print 'hello'

tr = WSGIContainer(app)


application = Application([
    (r"/TorTest", TorTest),
    (r".*", FallbackHandler, dict(fallback=tr)),
])



http_server = HTTPServer(application, xheaders=True)
http_server.listen(5000)
IOLoop.instance().start()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容