Python下HttpHTTPClient和AsyncHTTPClient

HTTPClient 使用例子:
    from tornado.httpclient import HTTPClient 

def synchronous_fetch(url):
     http_client = HTTPClient()
     response = http_client.fetch(url)
     return response.body



AsyncHTTPClient使用例子:

方法1:
from tornado.httpclient import AsyncHTTPClient

def asynchronous_fetch(url, callback):
  http_client = AsyncHTTPClient()
def handle_response(response): # 创建一个函数内的函数,来处理返回的结果
callback(response.body)
http_client.fetch(url, callback=handle_response)
# 异步处理结束后会调用指定的callback的函数


方法2:
from tornado.httpclient import AsyncHTTPClient
from tornado.concurrent import Future

def async_fetch_future(url):
http_client = AsyncHTTPClient()
my_future = Future()
fetch_future = http_client.fetch(url)
fetch_future.add_done_callback(lambda f: my_future.set_result(f.result()))
return my_future

方法3:
from tornado.httpclient import AsyncHTTPClient
from tornado import gen

@gen.coroutine #添加异步访问的装饰器
def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(url) # 获取异步结果时要使用yield
raise gen.Return(response.body) # 使用抛出异常的方式来返回结果,不能使用return来返回



以下知识是额外的可以了解下,但不保证知识是完整的:
  async and await 在python3.5,tornado4.3中可以了解下

  例子:
async deffetch_coroutine(url):
   http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
return response.body



使用yield来遍历异步的结果是,以下方法是在项目中没有试验过的
--------------------------------- start --------------------------------------
@gen.coroutine
def parallel_fetch(url1, url2): resp1, resp2 = yield [http_client.fetch(url1), http_client.fetch(url2)] @gen.coroutine def parallel_fetch_many(urls): responses = yield [http_client.fetch(url) for url in urls] # responses is a list of HTTPResponses in the same order @gen.coroutine def parallel_fetch_dict(urls): responses = yield {url: http_client.fetch(url) for url in urls} # responses is a dict {url: HTTPResponse}

--------------------------------- end ----------------------------------------


转载于:https://www.cnblogs.com/wind-wang/p/5649239.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值