python grequests极限_异步请求库之 grequests

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-31 03:46   35   0

GRequests允许您使用带有Gevent的请求来轻松地进行异步HTTP请求。

安装

pip install grequests

用法

import grequests

urls = [

'http://www.heroku.com',

'http://python-tablib.org',

'http://httpbin.org',

'http://python-requests.org',

'http://fakedomain/',

'http://kennethreitz.com'

]

rs = (grequests.get(u) for u in urls)

grequests.map(rs)

输出为:

[, , , , None, ]

如果在连接请求期间发生超时或任何其他异常,可以添加一个异常处理程序,该异常处理程序将在主线程内部使用请求和异常进行调用:

import grequests

def exception_handler(request, exception):

print ("Request failed")

reqs = [

grequests.get('http://httpbin.org/delay/1', timeout=0.001),

grequests.get('http://fakedomain/'),

grequests.get('http://httpbin.org/status/500')]

print(grequests.map(reqs, exception_handler=exception_handler))

输出为:

Request failed

Request failed

[None, None, ]

对于性能的提高,可使用imap,imap返回响应的生成器。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP