本文主要是介绍Python随记:【Python异步编程(五)】——多链接异步访问,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如果我们需要请求多个URL该怎么办呢,同步的做法访问多个URL只需要加个for循环就可以了。但异步的实现方式并没那么容易,在之前的基础上需要将hello()包装在asyncio的Future对象中,然后将Future对象列表作为任务传递给事件循环。
异步实现:
import time
import asyncio
from aiohttp import ClientSessiontasks = []
url = "https://www.baidu.com/{}"
async def hello(url):async with ClientSession() as session:async with session.get(url) as response:response = await response.read()print('Hello World:%s' % time.time())def run():for i in range(5):task = asyncio.ensure_future(hello(url.format(i)))tasks.append(task)if __name__ == '__main__':loop = asyncio.get_event_loop()run()loop.run_until_complete(asyncio.wait(tasks))## 输出:
>> Hello World:1527754874.8915546
>> Hello World:1527754874.899039
>> Hello World:1527754874.90004
>> Hello World:1527754874.9095392
>> Hello World:1527754874.9190395
搜集http响应:
把响应一一收集到一个列表中,最后保存到本地或者打印出来,可通过asyncio.gather(*tasks)将响应全部收集起来:
import time
import asyncio
from aiohttp import ClientSessiontasks = []
url = "https://www.baidu.com/{}"
async def hello(url):async with ClientSession() as session:async with session.get(url) as response:
# print(response)print('Hello World:%s' % time.time())return await response.read()def run():for i in range(5):task = asyncio.ensure_future(hello(url.format(i)))tasks.append(task)result = loop.run_until_complete(asyncio.gather(*tasks))print(result)if __name__ == '__main__':loop = asyncio.get_event_loop()run()输出:
>> Hello World:1527765369.0785167
>> Hello World:1527765369.0845182
>> Hello World:1527765369.0910277
>> Hello World:1527765369.0920424
>> Hello World:1527765369.097017
>> [b'<!DOCTYPE html>\r\n<!--STATUS OK-->\r\n<html>\r\n<head>\r\n......
这篇关于Python随记:【Python异步编程(五)】——多链接异步访问的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!