使用tornado AsyncHTTPClient异步访问第三方资源

前言:

描述下一个场景,可能由于权限和各种的限制导致,不是所有人都可以查询想要的信息,比如他的资产。然而我这边也不能直接从库里面查询,也是要通过申请好rest的去访问。

这不用说的那么多,大家做平台开发的时候,一定会遇到去访问远端的数据,如果你用tornaod的话,就可以用httpclient的异步模式了。

简单说下,什么是httpclient包? httpclient包是tornaod自带的http客户端,你可以想象成为curl和urllib2,他们所具备的功能,httpclient也都有的。

Hello, 又见面了,标注下链接,如果想看更多的关于Tornado的文章,请点击: http://blog.xiaorui.cc/?s=tornado

tornado的httpclient包,包含了两个模块,一个是同步的访问,一个是异步的访问。

http_client = AsyncHTTPClient()

这个是异步非阻塞的 http客户端, 这种方法需要提供 callback,当然他的异步是在tornado的体系里面体现出来的。

http_client = httpclient.HTTPClient()

这个同步阻塞的 http客户端, 这个完全就是同步的,也就是说,他堵塞了后,别人就不能在访问了。

这里简单说下他的用法:

用法很简单,这里的handle_reques是回调,也就是说,我访问了后产生了io堵塞,我会扔到后面,他自己搞定了后,直接会去调用handle_request的函数。

import tornado.ioloopfrom tornado.httpclient import AsyncHTTPClientdef handle_request(response):    '''callback needed when a response arrive'''    if response.error:        print "Error:", response.error    else:        print 'called'        print response.bodyhttp_client = AsyncHTTPClient() # we initialize our http client instancehttp_client.fetch("http://xiaorui.cc", handle_request) # here we try                    # to fetch an url and delegate its response to callbacktornado.ioloop.IOLoop.instance().start() # start the tornado ioloop to                    # listen for events

大家可以多加上几个访问很慢的网站或者是根本不能访问的网站测试下。

#xiaorui.ccimport tornado.ioloopfrom tornado.httpclient import AsyncHTTPClientdef handle_request(response):    '''callback needed when a response arrive'''    if response.error:        print "Error:", response.error    else:        print 'called'        print response.bodyhttp_client = AsyncHTTPClient()for i in range(10):                                                   http_client.fetch("http://10.58.101.248/testsleep", handle_request)tornado.ioloop.IOLoop.instance().start()

在服务端看到的日志是并发请求过来的。

大体的功能大家都了解了,现在说说用httpclient 常用的用法:

超时,这个很常用吧。

http_client.fetch("http://www.youtube.com",request_timeout=3,callback=self.on_fetch)

通过httpclient调用别人的接口,get post参数。

from tornado.httputil import url_concatparams = {"a": 1, "b": 2}url = url_concat("http://xiaorui.cc/", params)http_client = AsyncHTTPClient()http_client.fetch(url, request_callback_handler)

有些接口需要你提交当前的cookie通过

login_cookies = response.headers.get_list('Set-Cookie')request = httpclient.HTTPRequest(        url='url',    #这里的url想要有东西就需要带着cookie        method='GET',        headers=self.__login_headers, #在这里携带cookie信息)

就先这样了~ 有机会再进行补充下 ~

使用tornado AsyncHTTPClient异步访问第三方资源

相关文章:

你感兴趣的文章:

标签云: