python gevent async_python的异步初体验(gevent、async、await)
網絡爬蟲,這種io高密集型的應用由于大部分的時間在等待響應方面,所以CPU的使用率一直不高,速度也不快,為了解決這些問題,我們使用異步的方式來進行爬蟲程序。
串行的時候,如果我們要爬一個網站,那么我們通常都是一頁的內容完成了,再到下一頁,這樣的話,CPU的90%以上的時間用在了等待網頁響應上面。
異步的話,我們可以同時發起多個請求,一個請求發起了之后就不等待這個請求的響應,馬上發起第二個請求,第三個請求......
然后響應過來的內容我們再一個個進行處理,這樣的效率就高了很多。
舉個栗子:
首先我們搭建一個flask的服務器,故意降低它的響應速度:
from flask import Flask
import time
app = Flask(__name__)
@app.route('/')
def hello_world():
# 休眠三秒,展示異步的速度
time.sleep(3)
return 'Hello World!'
if __name__ == '__main__':
app.run(threaded=True)
首先我們使用python 3.5以上版本的async、await以及異步http請求庫aiohttp:
import asyncio
import time
import aiohttp
start = time.time()
async def get(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as res:
print(res.status)
text = await res.text()
return text
async def hello():
url = "http://127.0.0.1:5000/"
print('Waiting for',url)
res = await get(url)
print('Result:',res)
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(hello()) for i in range(5)]
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print('Cost time:',end-start)
使用python的第三方庫:gevent也可以實現網絡異步:
from gevent import monkey
# 猴子補丁一定要先打,不然就會報錯
monkey.patch_all()
import gevent
import requests
import time
def get(url):
print("Get from: ",url)
r = requests.session()
res = r.get(url)
print(res.status_code,url,res.text)
def synchronous_times(url):
start = time.time()
for i in range(5):
get(url)
end = time.time()
print("同步執行的時間:", start-end)
def asynchronous_times(url):
start = time.time()
gevent.joinall([gevent.spawn(get,url) for i in range(5)])
end = time.time()
print("異步執行的時間:", start-end)
synchronous_times("http://127.0.0.1:5000/")
asynchronous_times("http://127.0.0.1:5000/")
以上就使用aiohttp、genvent實現了異步的網絡請求。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python gevent async_python的异步初体验(gevent、async、await)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爱咬吸管的人五大特点
- 下一篇: 一盎司是多少克