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 attribute from the response to use from requests?
You can either use the
response.rawfile object, or iterate over the response.To use the
response.rawfile-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by setting thedecode_contentattribute toTrue(requestssets it toFalseto control decoding itself). You can then useshutil.copyfileobj()to have Python stream the data to a file object:To iterate over the response use a loop; iterating like this ensures that data is decompressed by this stage:
This’ll read the data in 128 byte chunks; if you feel another chunk size works better, use the
Response.iter_content()method with a custom chunk size:Note that you need to open the destination file in binary mode to ensure python doesn’t try and translate newlines for you. We also set
stream=Trueso thatrequestsdoesn’t download the whole image into memory first.