tornado 异步客户端 AsyncHTTPClient
前面了解Tornado的异步任务的常用做法,姑且归结为异步服务。通常在我们的服务内,还需要异步的请求第三方服务。针对HTTP请求,Python的库Requests是最好用的库,没有之一。官网宣称:HTTP for Human。然而,在tornado中直接使用requests将会是一场恶梦。requests的请求会block整个服务进程。
上帝关上门的时候,往往回打开一扇窗。Tornado提供了一个基于框架本身的异步HTTP客户端(当然也有同步的客户端)— AsyncHTTPClient。
AsyncHTTPClient 基本用法
AsyncHTTPClient是 tornado.httpclinet 提供的一个异步http客户端。使用也比较简单。与服务进程一样,AsyncHTTPClient也可以callback和yield两种使用方式。前者不会返回结果,后者则会返回response。
如果请求第三方服务是同步方式,同样会杀死性能。
class SyncHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
url = 'https://api.github.com/'
resp = requests.get(url)
print resp.status_code
self.finish('It works')
使用 AsyncHTTPClient
使用 yield协程 返回respond,这个虽然使用了异步,但是挂起了任务,类似阻塞,少量还可以,大量性能就下降了
@tornado.gen.coroutine
def AsyncGet(self, url,timeout=7):
Authorization = self.__Create_AuthorizationText()
headers = {'Content-Type': 'application/json','Authorization': Authorization}
http_client = tornado.httpclient.AsyncHTTPClient()
resp = yield http_client.fetch(url,method='GET',headers=headers,request_timeout=timeout)
raise tornado.gen.Return(resp.body)
所以callback的方式是性能最高的
def AsyncPost(self, url, params,timeout=7):
Authorization = self.__Create_AuthorizationText()
headers = {'Content-Type': 'application/json', 'Authorization': Authorization}
http_client = tornado.httpclient.AsyncHTTPClient()
body = JsonHelper.encode(params)
req = tornado.httpclient.HTTPRequest(
url=url,
method='POST',
headers=headers,
request_timeout=timeout,
body=body,
validate_cert=False)
http_client.fetch(req, callback=self.handler_response)
def AsyncGetClient(self, url,timeout=7):
Authorization = self.__Create_AuthorizationText()
headers = {'Content-Type': 'application/json','Authorization': Authorization}
http_client = tornado.httpclient.AsyncHTTPClient()
http_client.fetch(url,callback=self.handler_response,method='GET',headers=headers,request_timeout=timeout)
# raise tornado.gen.Return(resp.body)
def handler_response(self, response):
print response.body
self.log.info(response.body)
总结
通过AsyncHTTPClient的使用方式,可以轻松的实现handler对第三方服务的请求。结合前面关于tornado异步的使用方式。无非还是两个key。是否需要返回结果,来确定使用callback的方式还是yield的方式。当然,如果不同的函数都yield,yield也可以一直传递。这个特性,tornado的中的tornado.auth 里面对oauth的认证。