python异步请求库grequest安装和使用

安装

pip install grequests

使用

grequests实际上就是封装了gevent里面的方法,然后配合requests实现异步的IO

  • 所谓「异步 IO」,就是你发起一个 IO 操作,却不用等它结束,你可以继续做其他事情,当它结束时,你会得到通知。

import grequests, time

nowtime = time.time()
url = "https://blog.csdn.net/u011342224/article/details/{}"
detail_list = ['94603283', '79709322', '78959345', '78879633', '79414893']
# 生成一任务列表
tasks = (grequests.get(url.format(i)) for i in detail_list)


def exception_handler(request, exception):
    print("request failed")

# imap 不按顺序执行 
gr = grequests.imap(tasks, exception_handler=exception_handler)
print([len(i.text) for i in gr], time.time() - nowtime)

使用gevent 和 request 实现异步

import gevent
import requests
from gevent import monkey
# socket发送请求以后就会进入等待状态,gevent更改了这个机制
# socket.setblocking(False)  -->发送请求后就不会等待服务器响应
monkey.patch_all()  # 找到内置的socket并更改为gevent自己的东西
 
def fetch_async(method, url, req_kwargs):
    print(method, url, req_kwargs)
    response = requests.request(method=method, url=url, **req_kwargs)
    print(response.url, response.content)
 
# ##### 发送请求 #####
gevent.joinall([
    # 这里spawn是3个任务[实际是3个协程],每个任务都会执行fetch_async函数
    gevent.spawn(fetch_async, method='get', url='https://blog.csdn.net/u011342224/article/details/94603283', req_kwargs={}),
    gevent.spawn(fetch_async, method='get', url='https://blog.csdn.net/u011342224/article/details/78959345', req_kwargs={}),
    gevent.spawn(fetch_async, method='get', url='https://blog.csdn.net/u011342224/article/details/79414893', req_kwargs={}),
])
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值