AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
Python download image9/13/2023 ![]() But when I did a profile on this simple function, I found that it uses so many function calls compared to urllib and urllib2. I first tried the answer of Martijn Pieters, and it works well. ![]() I have the same need for downloading images using requests. We also set stream=True so that requests doesn't download the whole image into memory first. Note that you need to open the destination file in binary mode to ensure python doesn't try and translate newlines for you. This'll read the data in 128 byte chunks if you feel another chunk size works better, use the er_content() method with a custom chunk size: r = requests.get(settings.STATICMAP_URL.format(**data), stream=True) To iterate over the response use a loop iterating like this ensures that data is decompressed by this stage: r = requests.get(settings.STATICMAP_URL.format(**data), stream=True) R = requests.get(settings.STATICMAP_URL.format(**data), stream=True) You can then use pyfileobj() to have Python stream the data to a file object: import requests You can force it to decompress for you anyway by setting the decode_content attribute to True ( requests sets it to False to control decoding itself). To use the response.raw file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can either use the response.raw file object, or iterate over the response.
0 Comments
Read More
Leave a Reply. |