Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download images with aiohttp?

Tags:

So I have a discord bot that I'm playing with to learn Python. I have a command that downloads images, and edits/merges them, then sends the edited image to chat. I was using requests to do this before, but I was told by one of the library devs for discord.py that I should be using aiohttpinstead of requests. I can't find how to download images in aiohttp, I've tried a bunch of stuff, but none of it works.

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) 

is what I have right now, but that still doesn't work.

So, is there a way to download images?

like image 680
link2110 Avatar asked Feb 14 '16 04:02

link2110


1 Answers

You lock loop when write file. You need use 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() 
like image 107
Alexey Panevin Avatar answered Sep 22 '22 02:09

Alexey Panevin