如何用aiohttp下载图像?

时间:2016-02-14 04:21:30

标签: python aiohttp

所以我有一个与我一起学习Python的不和谐机器人。我有一个下载图像,编辑/合并它们的命令,然后将编辑后的图像发送到聊天室。我以前使用requests来执行此操作,但是我被一个图书馆开发人员告知discord.py我应该使用aiohttp而不是requests。我无法找到如何在aiohttp中下载图片,我尝试了很多东西,但都没有。

if message.content.startswith("!async"):
    import aiohttp
    import random
    import time
    import shutil
    start = time.time()
    notr = 0
    imagemake = Image.new("RGBA",(2048,2160))
    imgsave = "H:\Documents\PyCharmProjects\ChatBot\Images"
    imagesend = os.path.join(imgsave,"merged.png")
    imgmergedsend =os.path.join(imgsave,"merged2.png")
    with aiohttp.ClientSession() as session:
        async with session.get("http://schoolido.lu/api/cards/788/") as resp:
            data = await resp.json()
            cardsave = session.get(data["card_image"])
            with open((os.path.join(imgsave, "card.png")),"wb") as out_file:
                shutil.copyfileobj(cardsave, out_file)

是我现在所拥有的,但仍然无法奏效。

那么,有没有办法下载图片?

2 个答案:

答案 0 :(得分:7)

我刚才想出来了:

if message.content.startswith("!async2"):
    import aiohttp
    with aiohttp.ClientSession() as session:
        async with session.get("http://schoolido.lu/api/cards/788/") as resp:
            data = await resp.json()
            card = data["card_image"]
            async with session.get(card) as resp2:
                test = await resp2.read()
                with open("cardtest2.png", "wb") as f:
                    f.write(test)

我收到了回复,而非图片回复

答案 1 :(得分:6)

您在写入文件时锁定循环。您需要使用aiofiles。

import aiohttp        
import aiofiles

async with aiohttp.ClientSession() as session:
    url = "http://host/file.img"
    async with session.get(url) as resp:
        if resp.status == 200:
            f = await aiofiles.open('/some/file.img', mode='wb')
            await f.write(await resp.read())
            await f.close()