之前在编QQ机器人程序时用requests,遇到下载图片线程就阻塞住了,不得不学一下aiohttp,然后现在发现好像也不难嘛

教程官方教程就够了:
https://docs.aiohttp.org/en/latest/client.html

案例:

import aiohttp
import aiofiles
import asyncio


async def yiyan():
    '''简单的get请求'''
    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.n-1.cn/yiyan') as response:
            print(await response.text())


async def acgpic1(name):
    '''下载是异步的'''
    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.n-1.cn/ACG') as response:
            print(f'下载{name}中...')
            pic = await response.read()
            print(f'{name}下载完成')
            with open(f'{name}.jpg', 'wb+') as f:
                f.write(pic)
                print(f'{name}保存完毕')


async def acgpic2(name):
    '''下载是异步的 保存也是异步的(虽然这里没体现出来)'''
    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.n-1.cn/ACG') as response:
            print(f'下载{name}中...')
            pic = await response.read()
            print(f'{name}下载完成')
            async with aiofiles.open(f'{name}.jpg', 'wb') as f:
                print(f'{name}保存中...')
                await f.write(pic)
                print(f'{name}保存完毕')


loop = asyncio.get_event_loop()
task = [acgpic1(i) for i in range(10)]
loop.run_until_complete(asyncio.wait(task))
Last modification:December 30th, 2019 at 03:18 pm