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
- tornado coroutine使用
- 使用tornado的coroutine进行编程
- 使用tornado的coroutine进行编程
- 使用tornado的gen.coroutine进行异步编程
- tornado协程(coroutine)原理
- tornado.gen.coroutine-协程
- python tornado coroutine 原理
- tornado协程(coroutine)
- tornado协程(coroutine)原理
- tornado的asynchronous / coroutine进行异步编程
- tornado.gen.coroutine-编写异步函数
- Tornado使用
- coroutine
- coroutine
- Coroutine
- Lua Coroutine 的简单使用
- tornado 使用小技巧
- Tornado 使用经验
- 经典问题一.(插入乘号的整数划分)整数划分(四) nyoj 746
- A+B
- react-native for mac path setting
- final, finally, finalize的区别
- 计算IP地址以及CIDR
- tornado coroutine使用
- 收藏的js问题地址
- 整理VS下的一些常见警告
- gulp安装基础教程
- 我开始在CSDN上写博客啦!!!
- 面向对象之经典讲解一(继承,多态,super关键字)
- Eigen安装及Qt下安装测试
- 取名法则
- java给图片添加水印