If you want to download images using requests you can use the response.raw file object or iterate over the response.
Below is the code that shows how we use response.raw from the requests module:-
import requests
import shutil
r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
If you want the second method, so to iterate over the response you need to use a loop:
r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
for chunk in r:
f.write(chunk)
The above code will read the data in 128-byte chunks.
One important point to note that you need to open the destination file in binary mode to ensure python doesn't try and translate newlines for you. And you also need to set the stream=True so that requests don't download the whole image into memory first.