When building web applications in Python, you'll often need to download images or files from another server. The aiohttp library makes this easy with asynchronous requests.
Why Asynchronous Requests?
Synchronous requests block the execution of your code until the response is received. With
This allows you to make multiple requests in parallel very efficiently. This is perfect for fetching multiple images!
Basic Usage
First install
pip install aiohttp
Then we can fetch an image like so:
import aiohttp
import asyncio
async def get_image(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
image_bytes = await response.read()
return image_bytes
loop = asyncio.get_event_loop()
image_data = loop.run_until_complete(get_image('https://example.com/image.png'))
The key things to note:
This will download the image in the background without blocking our code!
Streaming Responses
For very large images, we may want to stream the response to avoid loading the entire file into memory.
We can do this by iterating through the response content instead of calling
async with response:
async for chunk in response.content.iter_chunked(1024):
f.write(chunk)
Handling Errors
We can catch exceptions from the request using normal
try:
async with session.get(url) as response:
image = await response.read()
except aiohttp.ClientConnectorError:
print("Connection error")
This covers the basics of fetching images asynchronously with aiohttp!