aiohttp 多任务异步协程

flask服务器.py

import time
from flask import Flask

app = Flask(name)

@app.route('/bobo')
def index_bobo():
time.sleep(2)
return 'Hello bobo!'
@app.route('/jay')
def index_jay():
time.sleep(2)
return 'Hello jay'
@app.route('/tom')
def index_tom():
time.sleep(2)
return 'hello tom'
if name == 'main':
app.run(threaded=True)

多任务异步协程.py

import requests
import asyncio
import time
import aiohttp

start = time.time()
urls = ['http://127.0.0.1:5000/bobo','http://127.0.0.1:5000/jay','http://127.0.0.1:5000/tom']

async def get_page(url):
async with aiohttp.ClientSession() as session:
async with await session.get(url) as response: # await 耗时操作手动挂起
# text() 方法返回字符串形式的数据
# read() 方法返回的是二进制形式的数据
# json() 方法返回的是json对象
# 注意: 获取响应数据操作之前一定要使用await进行手动挂起
page_text = await response.text()
print(page_text)

tasks = []

for url in urls:
c = get_page(url)
task = asyncio.ensure_future(c)
tasks.append(task)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

end = time.time()
print('总耗时',end - start)

posted @ 2021-02-24 22:27  未来全栈攻城狮  阅读(90)  评论(0编辑  收藏  举报