1、使用前提
将不支持异常的模板与asyncio结合使用【默认是使用线程池+事件循环】
2、同时下载3张图片的示例
1 # -*- coding: utf-8 -*- 2 """ 3 File Name : test 4 Description : 5 Author : Administrator 6 """ 7 import asyncio 8 import requests 9 10 11 async def download_image(url): 12 print('start task download', url) 13 14 loop = asyncio.get_running_loop() 15 16 future_obj = loop.run_in_executor(None, requests.get, url) 17 18 response = await future_obj 19 print('download success!') 20 21 # 保存相片的操作 22 file_name = url.rsplit('/', maxsplit=1)[-1] 23 with open(file_name, 'wb') as wf: 24 wf.write(response.content) 25 26 27 if __name__ == '__main__': 28 url_list = [ 29 'https://www.caoyuanfeng.com/up_files/tudou_06.jpg', 30 'https://www.caoyuanfeng.com/up_files/tudou_07.jpg', 31 'https://www.caoyuanfeng.com/up_files/tudou_08.jpg', 32 ] 33 34 tasks = [download_image(url) for url in url_list] 35 36 loop = asyncio.get_event_loop() 37 loop.run_until_complete(asyncio.wait(tasks))
3、总结
使用事件循环+线程池实现并发,比较更方便。
标签:__,异步,get,url,模块,download,loop,asyncio From: https://www.cnblogs.com/ygbh/p/16725959.html