关于aiohttp下载大文件的方式

版权声明: https://blog.csdn.net/dashoumeixi/article/details/88845137

这里给出一个例子.可自由发挥.

也可以直接使用aiofiles , 其实跟下面执行的代码差不多的. aiofiles 也是用线程池解决问题

#写入文件的函数. 用线程池解决
def save_file(fd , data):
    fd.write(data)



async def fetch_files(session:aiohttp.ClientSession,url:str,path:str):
    
    #打开文件
    fd = open(path, 'wb')
    #获取loop 
    lp = asyncio.get_event_loop()

    #获取响应
    async  with session.get(url) as resp:
        while True:
            
            #异步等待结果 , Chunk_size 每个分片大小
            data = await resp.content.read(CHUNK_SIZE)

            if not data:
                break

            #等待写入,在线程池中写入
            # run_in_executor 返回一个future,因此可等待
            await lp.run_in_executor(None,save_file,fd,data)
    fd.close()

猜你喜欢

转载自blog.csdn.net/dashoumeixi/article/details/88845137