tornado实现异步请求

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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容