如何用Python的grequests模块实现并发发送HTTP请求的示例?

2026-05-05 11:241阅读0评论SEO资讯
  • 内容介绍
  • 相关推荐

本文共计824个文字,预计阅读时间需要4分钟。

如何用Python的grequests模块实现并发发送HTTP请求的示例?

前言:requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但requests发送请求是串行的,即阻塞的。发送完一条请求才能发送下一条请求。为了提升测试效率,以下提供一种方法:

1. 使用线程(threading)或异步(asyncio)技术,实现并发发送请求。

2.使用队列(queue)来管理请求,避免请求冲突。

3.使用线程池或异步任务池来控制并发数量,防止过多并发导致服务器压力过大。

示例代码(使用线程):

python

import requestsfrom threading import Thread, Lockfrom queue import Queue

请求队列request_queue=Queue()

锁,用于同步lock=Lock()

def send_request(): while True: # 从队列中获取请求 url=request_queue.get() try: # 发送请求 response=requests.get(url) print(f请求成功:{url}) except Exception as e: print(f请求失败:{url},错误:{e}) finally: # 释放锁 lock.acquire() request_queue.task_done() lock.release()

创建线程threads=[]for i in range(10): # 假设并发数量为10 thread=Thread(target=send_request) thread.start() threads.append(thread)

添加请求到队列for url in [http://example.com] * 100: # 假设发送100条请求 request_queue.put(url)

等待队列中的请求全部完成request_queue.join()

等待线程结束for thread in threads: thread.join()

示例代码(使用异步):

pythonimport asyncioimport aiohttp

请求队列request_queue=Queue()

async def send_request(session, url): try: # 发送请求 async with session.get(url) as response: print(f请求成功:{url}) except Exception as e: print(f请求失败:{url},错误:{e})

async def main(): # 创建异步任务池 async with aiohttp.ClientSession() as session: tasks=[] for url in [http://example.com] * 100: # 假设发送100条请求 task=asyncio.create_task(send_request(session, url)) tasks.append(task) await asyncio.gather(*tasks)

运行异步任务asyncio.run(main())

如何用Python的grequests模块实现并发发送HTTP请求的示例?

以上两种方法都可以实现并发发送请求,提高测试效率。根据实际需求选择合适的方法。

前言

requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但是requests发送请求是串行的,即阻塞的。发送完一条请求才能发送另一条请求。
为了提升测试效率,一般我们需要并行发送请求。这里可以使用多线程,或者协程,gevent或者aiogithub.com/spyoungtech/grequests

grequests简单使用

首先构造一个请求列表,使用grequests.map()并行发送,得到一个响应列表。示例如下。

import grequests req_list = [ # 请求列表 grequests.get('github.com') for i in range(100)] print(time.time()-start)

实际耗时约100s+

使用grequests发送

import grequests import time start = time.time() req_list = [grequests.get('github.com') for i in range(100)] res_list = grequests.map(req_list) print(time.time()-start)

际耗时约3.58s

异常处理

在批量发送请求时难免遇到某个请求url无法访问或超时等异常,grequests.map()方法还支持自定义异常处理函数,示例如下。

import grequests def err_handler(request, exception): print("请求出错") req_list = [ grequests.get('fakedomain/'), # 该域名不存在 grequests.get('httpbin.org/status/500') # 正常返回500的请求 ] res_list = grequests.map(reqs, exception_handler=err_handler) print(res_list)

运行结果:

请求出错
请求出错
[None, None, <Response [500]>]

以上就是Python使用grequests并发发送请求的示例的详细内容,更多关于Python grequests发送请求的资料请关注易盾网络其它相关文章!

本文共计824个文字,预计阅读时间需要4分钟。

如何用Python的grequests模块实现并发发送HTTP请求的示例?

前言:requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但requests发送请求是串行的,即阻塞的。发送完一条请求才能发送下一条请求。为了提升测试效率,以下提供一种方法:

1. 使用线程(threading)或异步(asyncio)技术,实现并发发送请求。

2.使用队列(queue)来管理请求,避免请求冲突。

3.使用线程池或异步任务池来控制并发数量,防止过多并发导致服务器压力过大。

示例代码(使用线程):

python

import requestsfrom threading import Thread, Lockfrom queue import Queue

请求队列request_queue=Queue()

锁,用于同步lock=Lock()

def send_request(): while True: # 从队列中获取请求 url=request_queue.get() try: # 发送请求 response=requests.get(url) print(f请求成功:{url}) except Exception as e: print(f请求失败:{url},错误:{e}) finally: # 释放锁 lock.acquire() request_queue.task_done() lock.release()

创建线程threads=[]for i in range(10): # 假设并发数量为10 thread=Thread(target=send_request) thread.start() threads.append(thread)

添加请求到队列for url in [http://example.com] * 100: # 假设发送100条请求 request_queue.put(url)

等待队列中的请求全部完成request_queue.join()

等待线程结束for thread in threads: thread.join()

示例代码(使用异步):

pythonimport asyncioimport aiohttp

请求队列request_queue=Queue()

async def send_request(session, url): try: # 发送请求 async with session.get(url) as response: print(f请求成功:{url}) except Exception as e: print(f请求失败:{url},错误:{e})

async def main(): # 创建异步任务池 async with aiohttp.ClientSession() as session: tasks=[] for url in [http://example.com] * 100: # 假设发送100条请求 task=asyncio.create_task(send_request(session, url)) tasks.append(task) await asyncio.gather(*tasks)

运行异步任务asyncio.run(main())

如何用Python的grequests模块实现并发发送HTTP请求的示例?

以上两种方法都可以实现并发发送请求,提高测试效率。根据实际需求选择合适的方法。

前言

requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但是requests发送请求是串行的,即阻塞的。发送完一条请求才能发送另一条请求。
为了提升测试效率,一般我们需要并行发送请求。这里可以使用多线程,或者协程,gevent或者aiogithub.com/spyoungtech/grequests

grequests简单使用

首先构造一个请求列表,使用grequests.map()并行发送,得到一个响应列表。示例如下。

import grequests req_list = [ # 请求列表 grequests.get('github.com') for i in range(100)] print(time.time()-start)

实际耗时约100s+

使用grequests发送

import grequests import time start = time.time() req_list = [grequests.get('github.com') for i in range(100)] res_list = grequests.map(req_list) print(time.time()-start)

际耗时约3.58s

异常处理

在批量发送请求时难免遇到某个请求url无法访问或超时等异常,grequests.map()方法还支持自定义异常处理函数,示例如下。

import grequests def err_handler(request, exception): print("请求出错") req_list = [ grequests.get('fakedomain/'), # 该域名不存在 grequests.get('httpbin.org/status/500') # 正常返回500的请求 ] res_list = grequests.map(reqs, exception_handler=err_handler) print(res_list)

运行结果:

请求出错
请求出错
[None, None, <Response [500]>]

以上就是Python使用grequests并发发送请求的示例的详细内容,更多关于Python grequests发送请求的资料请关注易盾网络其它相关文章!