使用tornado httpclient的异步库AsyncHTTPClient构建中转接口

前言:


      我这里简单的描述一下中转接口,因为权限和各种的限制导致不是所以人都可以查询想要的信息,比如他的资产。然而我这边也不能直接从库里面查询,也是要通过rest的模式去访问。

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

       简单说下,什么是httpclient包? httpclient包是tornaod自带的http客户端,你可以相称curl和urllib2,他们有的功能httpclient也都有的。


更多文章请关注我的个人站点, xiaorui.cc


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


http_client = AsyncHTTPClient()

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


http_client = httpclient.HTTPClient()

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



这里简单说下他的用法:


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


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


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


wKiom1NJDDqRUow_AAIogRsu6Mg978.jpg


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


wKiom1NJDMDgN8gPAAZFMOb60dU962.jpg


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


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


超时,这个很常用吧。


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


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

from tornado.httputil import url_concat
params = {"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信息
)


好了,就说这么多了。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值