使用httpRequest太无脑了,太莽了,当希望使用异步request时,首先引入AsyncHttprequest
from tornado.httpclient import AsyncHTTPClient
将接口中的方法添加上tornado的协程符
@coroutine
根据request的方式(get或者post)封装参数
- get方法,封装url,分为三部分, host,接口路由以及参数串,其中接口路由和参数由 ‘?’ 分割
url = u'http://{}/{}?{}'.format(host, name, query_str)
- post方法, 将参数列表封装为dict,并用urlencode处理
args = {
'item_id': task['item_id'],
'code': status,
'message': message,
}
body = urllib.urlencode(args)
发送请求: 由于是异步方法,使用yield asyncHTTPClient().fetch()方法发送
参数列表:
- url:host+接口路由, 如是get方法还有参数json串
- method: =“GET”或“POST”
- body:仅限POST方法,内容为经过urlencode后的参数dict
- headers:{‘X-Requested-With’: ‘XMLHttpRequest’},非必填
- request_timeout: 超时,非必填
获取response内容:
使用safe_json_decode以及safte_typed_from_str来解析response
ret = yield AsyncHTTPClient().fetch(task['migr