tornado coroutine使用

来源:互联网 发布:俄军 知乎 编辑:程序博客网 时间:2024/05/20 05:30

工作中想在tornado里面封装个异步发送http请求的公共方法,代码如下:

@tornado.gen.enginedef asyn_send_http_req(reqUrl, parm):        try:            client = tornado.httpclient.AsyncHTTPClient()            httpReq = tornado.httpclient.HTTPRequest(reqUrl,method="POST",body=parm,connect_timeout=3)            response = yield tornado.gen.Task(client.fetch,httpReq)            response = response.body            logging.info(response)        except Exception:            response = None        if response and response.strip():            pass        else:            response = None
    yield response
response = asyn_send_http_req(reqUrl,parm)
获取响应总是报错,后来查了下资料,原来是generator里面不能return。需要使用tornado的 
tornado.gen.Task 来返回响应,代码如下:
@tornado.gen.enginedef asyn_send_http_req(reqUrl, parm,callback=None):        try:            client = tornado.httpclient.AsyncHTTPClient()            httpReq = tornado.httpclient.HTTPRequest(reqUrl,method="POST",body=parm,connect_timeout=3)            response = yield tornado.gen.Task(client.fetch,httpReq)            response = response.body            logging.info(response)        except Exception:            response = None        if response and response.strip():            pass        else:            response = None        callback(response)
response = yield tornado.gen.Task(asyn_send_http_req,reqUrl,parm)
使用callback返回响应。
@tornado.gen.engine 是3.0 版本前使用,现在不建议使用,3.0后使用@tornado.gen.coroutine替代。
@tornado.gen.coroutinedef asyn_send_http_req(reqUrl, parm):        try:            client = tornado.httpclient.AsyncHTTPClient()            httpReq = tornado.httpclient.HTTPRequest(reqUrl,method="POST",body=parm,connect_timeout=3)            response = yield tornado.gen.Task(client.fetch,httpReq)            response = response.body            logging.info(response)        except Exception:            response = None        if response and response.strip():            pass        else:            response = None        raise gen.Return(response)
同时使用gen.Return()方法返回响应。
OK,问题解决。

0 0
原创粉丝点击