python 解决访问慢的问题

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的认证。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值