Python学习---IO的异步[gevent+Grequests模块],,安装gevent模块
Python学习---IO的异步[gevent+Grequests模块],,安装gevent模块
安装gevent模块
pip3 install gevent
Gevent实例
import geventimport requestsfrom 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://www.python.org/‘, req_kwargs={}), gevent.spawn(fetch_async, method=‘get‘, url=‘https://www.yahoo.com/‘, req_kwargs={}), gevent.spawn(fetch_async, method=‘get‘, url=‘https://github.com/‘, req_kwargs={}),])
Gevent也是支持协程池
##### 发送请求(协程池控制最大协程数量) ###### 也可以理解为先最大发送2个请求,2个请求结束后发送第三个请求from gevent.pool import Poolpool = Pool(2) # 最多执行2个协程序,None表示不设置限制gevent.joinall([ pool.spawn(fetch_async, method=‘get‘, url=‘https://www.python.org/‘, req_kwargs={}), pool.spawn(fetch_async, method=‘get‘, url=‘https://www.yahoo.com/‘, req_kwargs={}), pool.spawn(fetch_async, method=‘get‘, url=‘https://www.github.com/‘, req_kwargs={}),])
Grequests
安装grequests
pip3 install grequests
grequests实际上就是封装了gevent里面的方法,然后配合requests实现异步的IO
grequests = gevent + request
grequests.map() 内部实现
Grequest实例
import grequests # 实际上就是requests + geventrequest_list = [ # 发送get请求 grequests.get(‘https://www.baidu.com/‘, timeout=10.001), grequests.get(‘https://www.taobao.com/‘), grequests.get(‘https://hao.360.cn/‘)]# ##### 执行并获取响应列表 #####response_list = grequests.map(request_list) # 实际上内部循环执行gevent内部的joinall()方法print(response_list)# ##### 执行并获取响应列表(处理异常) ###### def exception_handler(request, exception):# print(request,exception)# print("Request failed")# response_list = grequests.map(request_list, exception_handler=exception_handler)# print(response_list)
Python学习---IO的异步[gevent+Grequests模块]
相关内容
- Python 3 复习各种符号,,关键字(Keywor
- typeError:The value of a feed cannot be a tf.Tensor object.Acceptable
- [Python] Windows上通过pip安装uwsgi报错,,错误提示:Attri
- 吴裕雄 python 神经网络——TensorFlow 图像预处理完整样例
- Python--格式化cookie为字典类型,,import req
- 【python】Numpy中stack(),hstack(),vstack()函数详解,,转自
- python语音唤醒-pocketsphinx,,使用pocketsp
- Python+selenium之跳过测试和预期失败,,在运行测试时,需
- centos7 yum 安装 python3.6,,wget -O /e
- python中的easydict模块使用,,from easyd
评论关闭