grequests高性能的HTTP客户端-grequests

关于 grequests

众所周知,requests 出于 K神 之手,但它是串行的,在并发场景下效率会受到阻塞的影响而变得低下。他一度认为程序是为人设计的,这不,当人们需要异步发送请求,提高请求效率的时候,他又推出了全新的 grequests 库(仅 100 多行代码)。

grequests 是基于 geventrequests 开发的,效果和你单独使用 gevent 去发送 requests 请求基本一致,但是用 grequests 会简单上不少,何乐而不为呢?该说不说,K神 牛掰!

附:K神Github主页

走进 grequests

用过 requests 的兄弟对 grequests 不会陌生,因为你会发现用法极其相似。

安装

pip install grequests

例子

使用 grequests 异步请求百度

import grequests,time

url = 'https://www.baidu.com'
req_list = [
    grequests.get(url),
    grequests.get(url),
    grequests.get(url),
]

start_time=time.time()
res_list = grequests.map(req_list)
end_time=time.time()
print(res_list,end_time-start_time)

代码运行结果

使用 requests 串行请求百度

import  requests,time

url = 'https://www.baidu.com'
start_time=time.time()
res1 = requests.get(url)
res2 = requests.get(url)
res3 = requests.get(url)
end_time=time.time()

print([res1,res2,res3],end_time-start_time)

代码运行结果

对比分析

根据结果,你会发现,grequestsrequests 的功能完全一致,但是粗略估计 grequestsrequests 的性能提升 186% 不止。并发量越大,提升越大。

关于 grequests.map()

grequests.map()接收一个 AsyncRequest 列表对象,map 方法中会将这个列表转化为任务队列,然后交给 gevent 去异步执行。任务全部结束后返回一个 response 列表。

grequests.get的源码

grequests.map的源码

高级用法

自定义异常处理

import grequests,time

# 自定义错误处理程序,接收两个参数分别为request和exception
def err_handler(request,exception):
    print('发生异常,具体信息为:',exception)

url = 'https://www.not-ok.com'
req_list = [
    grequests.get(url),
    grequests.get(url),
    grequests.get(url),
]

start_time=time.time()

# 注意,err_handler在这里
res_list = grequests.map(req_list,exception_handler=err_handler)
end_time=time.time()
print(res_list,end_time-start_time)

代码运行结果

其他用法

通过源码我们了解到:

参数 解释
stream True 时,可以处理流文件(不会立即下载)。
size 流控参数,(指定并发量),如果不指定则不做限制。
exception_handler 自定义异常处理方法。
gtimeout gevent 的任务超时时间(所有任务)。

以上就是今天的全部内容了,感谢您的阅读,我们下节再会。

版权声明:除特殊说明,博客文章均为phyger原创,依据CC BY-SA 4.0许可证进行授权,转载请附上出处链接及本声明。来自:https://u1s1.vip/archives/124
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇