当前位置: 首页 > 工具软件 > GRequests > 使用案例 >

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

薛弘阔
2023-12-01

安装

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={}),
])
 类似资料: