Created
January 4, 2020 20:17
-
-
Save xjcl/61de979a63e8cb96685766cce1438c8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import asyncio | |
import aiohttp | |
import aiofiles | |
get_img_url = lambda i: 'https://cdn.discordapp.com/embed/avatars/' + str(i) + '.png' | |
def download_all_sync(): | |
for i in range(5): | |
with requests.get(get_img_url(i)) as resp: | |
with open(str(i) + '.png', 'wb') as file: | |
file.write(resp.content) | |
async def download_all_async(): | |
async def download_one(i): | |
async with aiohttp.ClientSession() as session: | |
async with session.get(get_img_url(i)) as resp: | |
async with aiofiles.open(str(i) + '.png', 'wb') as file: | |
await file.write(await resp.read()) | |
await asyncio.wait([asyncio.ensure_future(download_one(i)) for i in range(5)]) | |
# download_all_sync() | |
asyncio.get_event_loop().run_until_complete(download_all_async()) # pre-3.7 | |
# asyncio.run(download_all_async()) # Python 3.7+ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment