如何用aiohttp下载图像?

lin*_*110 8 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)
Run Code Online (Sandbox Code Playgroud)

是我现在所拥有的,但仍然无效.

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

小智 9

您在写入文件时锁定循环。您需要使用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()
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用“async with”而不是打开和关闭文件。例如 ```async with aiofiles.open(path, 'wb') as f: wait f.write(await resp.read())``` (3认同)

Fal*_*ght 8

pdf_url = 'https://example.com/file.pdf'
    
async with aiohttp.ClientSession() as session:
    async with session.get(pdf_url) as resp:
        if resp.status == 200:
            with open('file.pdf', 'wb') as fd:
                async for chunk in resp.content.iter_chunked(10):
                    fd.write(chunk)
Run Code Online (Sandbox Code Playgroud)

虽然 read()、json() 和 text() 方法非常方便,但您应该 谨慎使用它们。所有这些方法都将整个响应加载到 内存中。例如,如果您想下载几个千兆字节大小的文件,这些方法将加载内存中的所有数据。相反,您可以使用内容属性。它是 aiohttp.StreamReader 类的实例。gzip 和 deflate 传输编码会自动为您解码:

https://docs.aiohttp.org/en/stable/client_quickstart.html#streaming-response-content


lin*_*110 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)
Run Code Online (Sandbox Code Playgroud)

我收到了回复,而不是图片响应