2

Here is a body of code that works, taken from: https://stackoverflow.com/a/18043472

It uses the requests module in python to download an image.

import requests, shutil

url = 'http://example.com/img.png'
response = requests.get(url, stream=True)
with open('img.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response

Two questions I've been thinking about:

1) Why is it necessary to set stream=True? (I've tested it without that parameter and the image is blank) Conceptually, I don't understand what a streaming GET request is.

2) What's the difference between a raw response and a response? (Why is shutil.copyfileobj necessary, why can't I just directly write to file?)

Thanks!

Community
  • 1
  • 1
Victor Lin
  • 288
  • 1
  • 3
  • 10

1 Answers1

0

Quote from documentation:

If you set stream to True when making a request, Requests cannot release the connection back to the pool unless you consume all the data or call Response.close.

More info here.

PatNowak
  • 5,721
  • 1
  • 25
  • 31
  • Why am I unable to download an image without using a stream? What's the difference between using it and not using it? – Victor Lin Dec 03 '15 at 08:59
  • It should ensure that you can get the whole resource you request for, but it can lead to inefficiency with connections. – PatNowak Dec 03 '15 at 09:17