× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to download image using requests in Python

Martijn Pieters
Sep 05, 2014
<p>You can either use the <a href="http://docs.python-requests.org/en/latest/api/#requests.Response.raw"><code>response.raw</code> file object</a>, or <a href="http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content"><code>.iter_content()</code></a>, and iterate over the response.</p><p>To use the <code>response.raw</code> file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by setting the <code>decode_content</code> attribute to <code>True</code> (<code>requests</code> sets it to <code>False</code> to control decoding itself). You can then use <a href="https://docs.python.org/2/library/shutil.html#shutil.copyfileobj"><code>shutil.copyfileobj()</code></a> to have Python stream the data to a file object:</p><pre><code>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) </code></pre><p>To iterate over the response with <code>respones.iter_content()</code> use a loop; the method ensures that data is decompressed by this stage:</p><pre><code>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.iter_content(): f.write(chunk) </code></pre><p>This'll read the data in 128 byte chunks; if you feel another chunk size works better, do use <code>.iter_content()</code> with a custom chunk size:</p><pre><code>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.iter_content(1024): f.write(chunk) </code></pre><p>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 <code>stream=True</code> so that <code>requests</code> doesn't download the whole image into memory first.</p><p>This tip was originally posted on <a href="http://stackoverflow.com/questions/13137817/how-to-download-image-using-requests/13137873#13137873">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus