Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm trying to download and save an image from the web using python's requests module.

Here is the (working) code I used:

img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f:

f.write(img.read())

Here is the new (non-working) code using requests:

r = requests.get(settings.STATICMAP_URL.format(**data))

if r.status_code == 200:

img = r.raw.read()

with open(path, 'w') as f:

f.write(img)

Can you help me on what attributes from the response to use from requests?

1 Answer

0 votes
by (106k points)

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.

Related questions

Browse Categories

...