安裝gevent模塊html
pip3 install gevent
Gevent實例python
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://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也是支持協程池git
##### 發送請求(協程池控制最大協程數量) ##### # 也能夠理解爲先最大發送2個請求,2個請求結束後發送第三個請求 from gevent.pool import Pool pool = 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={}), ])
安裝grequestsgithub
pip3 install grequests
grequests實際上就是封裝了gevent裏面的方法,而後配合requests實現異步的IO sql
grequests = gevent + request 服務器
grequests.map() 內部實現 異步
Grequest實例socket
import grequests # 實際上就是requests + gevent request_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)