日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python gevent async_python的异步初体验(gevent、async、await)

發布時間:2023/12/2 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。