Python學習---IO的異步[asyncio +aiohttp模塊]

aiohttp

aiohttp是在asyncio模塊基礎上封裝的一個支持HTTP請求的模塊,內容比8.4.2【基於asyncio實現利用TCP模擬HTTP請求】更全面 html

安裝aiohttp:sql

pip3 install aiohttp

asyncio + aiohttp實現異步請求【有問題】異步

import aiohttp
import asyncio
@asyncio.coroutine
def fetch_async(url):
    print(url)
    response = yield from aiohttp.request('GET', url)
    # data = yield from response.read()
    # print(url, data)
    print(url, response)
    response.close()
tasks = [fetch_async('http://www.cnblogs.com/'), fetch_async('http://www.chouti.com/')]
event_loop = asyncio.get_event_loop()
results = event_loop.run_until_complete(asyncio.gather(*tasks))
event_loop.close()

image

asyncio + requests完成IO異步

asyncio + requests完成IO異步async

import asyncio
import requests
@asyncio.coroutine
def fetch_async(func, *args): 
    # 獲取事件循環:就是有個循環一直等待這用戶的響應
    loop = asyncio.get_event_loop()
    future = loop.run_in_executor(None, func, *args) # 執行傳遞進來的get函數
    response = yield from future
    print(response.url, response.content)
tasks = [
    fetch_async(requests.get, 'http://www.cnblogs.com/ftl1012/'),
    fetch_async(requests.get, 'http://dig.chouti.com/images/homepage_download.png')
]
loop = asyncio.get_event_loop()
results = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()

 

image

相關文章
相關標籤/搜索