tornado中的异步处理方案

tornado中的异步处理方法

  • tornado中有时候需要调用其他业务的rest接口,这个时候需要进行异步处理。
    • 一、requests的问题
    • 二、tornado中的异步

tornado中有时候需要调用其他业务的rest接口,这个时候需要进行异步处理。

一、requests的问题

在tornado的请求中如果使用了requests后,会发现requests阻塞了tornado。
例如下面这样的代码:

class test(tornado.web.RequestHandler):
    def get(self):
        self.write("error 404 ")
        print self.request.remote_ip
    def post(self):
        returndata = requests.post(http://127.0.0.1:9080/getreurn)
        self.write(returndata.content)

这里的post请求会被阻塞等待返回。
所以这个时候正确的做法是应该使用异步方法。这里异步其实可以unirest等,也可以使用tornado来实现

二、tornado中的异步

import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.ioloop
import tornado.web
import tornado.gen
import tornado.options
import tornado.httpclient
import tornado.concurrent
class test(tornado.web.RequestHandler):
    def get(self):
        self.write("error 404 ")
        print self.request.remote_ip

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_req = tornado.httpclient.HTTPRequest(url='http://127.0.0.1:9080/getreurn', method='POST',body=json.dumps(data),headers={'Content-Type':'application/json'}, request_timeout=15)
        response = yield tornado.gen.Task(http_client.fetch, http_req)
        print response.body
        self.write(response.body)

注意看到函数上的装饰器
@tornado.web.asynchronous
@tornado.gen.coroutine
这两个装饰器是用来下面异步和生成器使用的。否则生成器会报错
tornado.gen.Task
是tornado用来迭代执行请求对象以及内容的部分

http_client = tornado.httpclient.AsyncHTTPClient()
http_req = tornado.httpclient.HTTPRequest(url=‘http://127.0.0.1:9080/getreurn’, method=‘POST’,body=json.dumps(data),headers={‘Content-Type’:‘application/json’}, request_timeout=15)
一个是异步客户端 一个是请求,通过response = yield tornado.gen.Task(http_client.fetch, http_req) 来返回响应对象。
后续继续处理返回结果即可。

你可能感兴趣的:(python,tornado)