首先搭建一个简易的flask页面,如下:
from flask import Flask
import time
from flask import Flask
import time
app = Flask(__name__)
@app.route('/111')
def index_1():
time.sleep(1)
return 'Hello 111'
@app.route('/222')
def index_2():
time.sleep(1)
return 'Hello 222'
@app.route('/333')
def index_3():
time.sleep(1)
return 'Hello 333'
@app.route('/444')
def index_4():
time.sleep(1)
return 'Hello 444'
if __name__ == '__main__':
app.run(threaded=True)
接下来就是aiohttp实现异步请求的代码页面:
import time
import aiohttp
import asyncio
# 计时
start = time.time()
# 定义一个协程对象,async表示定义一个协程对象,with表示安全打开和自动关闭模式
async def http(url):
async with aiohttp.ClientSession() as session:
# await表示阻塞挂起
async with await session.get(url) as respond:
print(await respond.text())
urls = [
'http://127.0.0.1:5000/111',
'http://127.0.0.1:5000/222',
'http://127.0.0.1:5000/333',
'http://127.0.0.1:5000/444'
]
# 准备一个tasks数组
tasks = []
# 对协程对象进行封装为task
for url in urls:
cop = http(url)
task = asyncio.ensure_future(cop)
tasks.append(task)
# 把task注册到时间循环中
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print('总耗时:', end-start)